2012-03-04 83 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]; 
} 
}