在編寫PHP模板引擎工具類時,以前常用的一個正則替換函數為 preg_replace(),加上正則修飾符 /e,就能夠執行強大的回調函數,實現模板引擎編譯(其實就是字符串替換)。
詳情介紹參考博文:PHP函數preg_replace() 正則替換所有符合條件的字符串
應用舉例如下:
public function compile($template) {
// if邏輯
$template = preg_replace("//</!/-/-/{if/s+(.+?)/}/-/-/>/e", "/$this->ifTag('//1')", $template);
return $template;
}
/**
* if 標簽
*/
protected function ifTag($str) {
//$str = stripslashes($str); // 去反轉義
return '<?php if (' . $str . ') { ?>';
}
}
$template = 'xxx<!--{if $user[/'userName/']}-->yyy<!--{if $user["password"]}-->zzz';
$tplComplier = new Template();
$template = $tplComplier->compile($template);
echo $template;
?>
輸出結果為:
仔細觀察,發現 $user["password"] 中的雙引號被轉義了,這不是我們想要的結果。
為了能夠正常輸出,還必須反轉義一下,但是,如果字符串中本身含有反轉義雙引號的話,我們此時反轉義,原本的反轉義就變成了非反轉義了,這個結果又不是我們想要的,所以說這個函數在這方面用的不爽!
后來,發現一個更專業級的 正則替換回調函數 preg_replace_callback()。
回調函數 callback:
一個回調函數,在每次需要替換時調用,調用時函數得到的參數是從subject 中匹配到的結果。回調函數返回真正參與替換的字符串。這是該回調函數的簽名:
像上面所看到的,回調函數通常只有一個參數,且是數組類型。
羅列一些有關preg_replace_callback()函數的實例:
Example #1 preg_replace_callback() 和 匿名函數
如果回調函數是個匿名函數,在PHP5.3中,通過關鍵字use,支持給匿名函數傳多個參數,如下所示:
Example #2 preg_replace_callback() 和 一般函數
?>
Example #3 preg_replace_callback() 和 類方法
如何在類的內部調用非靜態函數?你可以按如下操作:
對于 PHP 5.2,第二個參數 像這樣 array($this, 'replace') :
private function process($text){
$reg = "//{([0-9a-zA-Z/- ]+)/:([0-9a-zA-Z/- ]+):?/}/";
return preg_replace_callback($reg, array($this, 'replace'), $text);
}
private function replace($matches){
if (method_exists($this, $matches[1])){
return @$this->$matches[1]($matches[2]);
}
}
}
?>
對于 PHP5.3,第二個參數像這樣 "self::replace" :
注意,也可以是 array($this, 'replace')。
private function process($text){
$reg = "//{([0-9a-zA-Z/- ]+)/:([0-9a-zA-Z/- ]+):?/}/";
return preg_replace_callback($reg, "self::replace", $text);
}
private function replace($matches){
if (method_exists($this, $matches[1])){
return @$this->$matches[1]($matches[2]);
}
}
}
?>
根據上面所學到的知識點,把模板引擎類改造如下:
public function compile($template) {
// if邏輯
$template = preg_replace_callback("//</!/-/-/{if/s+(.+?)/}/-/-/>/", array($this, 'ifTag'), $template);
return $template;
}
/**
* if 標簽
*/
protected function ifTag($matches) {
return '<?php if (' . $matches[1] . ') { ?>';
}
}
$template = 'xxx<!--{if $user[/'userName/']}-->yyy<!--{if $user["password"]}-->zzz';
$tplComplier = new Template();
$template = $tplComplier->compile($template);
echo $template;
?>
輸出結果為:
正是我們想要的結果,雙引號沒有被反轉義!
新聞熱點
疑難解答