2012-03-04 61 views
1

我正在使用preg_mat来替换模板中的if语句。我一直试图从preg_match_all获得匹配,并从匹配中获得结果并使用preg_replace,但是我得到了偏移错误。使用preg_match_all结果preg_replace的问题

任何语法的帮助将不胜感激。也很好奇,如果有更好的方式去做这件事。

代码示例:

public function output() { 

$output = file_get_contents($this->file); 

foreach ($this->values as $key => $value) { 
    $tagToReplace = "[@$key]"; 
    $output = str_replace($tagToReplace, $value, $output); 

    $dynamic = preg_quote($key); 
    $pattern = '%\[if @'.$dynamic.'\](.*?)\[/if\]%'; // produces: %\[if @username\](.*?)\[/if\]% 

    if ($value == '') { 
    $output = preg_replace($pattern, "", $output); 
    } else { 
    preg_match_all($pattern, $output, $if_match); 
    $output = preg_replace("%\[if @".$dynamic."\]%", "", $if_match[0][0]); 
    $output = preg_replace("%\[/if]%", "", $if_match[0][0]);   
    } 

模板除外:

[if @username] <p>A statement goes here and this is [@username]</p> [/if] 
    [if @sample] <p>Another statement goes here</p> [/if] 

控制器摘录:

$layout->set("username", "My Name"); 
$layout->set("sample", ""); 
+0

在这一点上,你应该考虑只使用一个工作模板引擎。 (您之前的preg_replace_callback方法并不聪明,但比这种逐步式字符串变形更有意义。) – mario 2012-03-04 20:53:28

+0

谢谢 - 这就是我下一次尝试的方法。这是一个非常小的简历模板引擎。我很了解Smarty,但我将这部分做为学习体验。 – jsuissa 2012-03-04 20:59:03

回答

0

使用回调,然后在$匹配运行的preg_replace解决了这个问题:

public function output() { 

$output = file_get_contents($this->file); 

foreach ($this->values as $key => $value) { 
    $tagToReplace = "[@$key]"; 
    $output = str_replace($tagToReplace, $value, $output); 

    $dynamic = preg_quote($key); 
    $pattern = '%\[if @'.$dynamic.'\](.*?)\[/if\]%'; // produces: %\[if @username\](.*?)\[/if\]% 

    if ($value == '') { 
    $output = preg_replace($pattern, "", $output); 
    } else { 
    $callback = new MyCallback($key, $value); 
    $output = preg_replace_callback($pattern, array($callback, 'callback'), $output); 
    } 

} 

return $output; 
} 


} 

class MyCallback { 
private $key; 
private $value; 

function __construct($key, $value) { 
    $this->key = $key; 
    $this->value = $value; 
} 

public function callback($matches) { 

    $matches[1] = preg_replace("%\[if @".$this->key."\]%", "", $matches[1]); 
    $matches[1] = preg_replace("%\[/if]%", "", $matches[1]); 

    return $matches[1]; 
} 
}