php7中使用preg_replace_callback()替代preg_replace()

php7中,preg_replace()再也不支持"\e" (PREG_REPLACE_EVAL),須要使用preg_replace_callback()來代替。php

 

看例子來講吧php7

$content = preg_replace("/{#(.+?)}/eis", '$lang[\'\\1\']', $content) ;函數

這是原來的代碼,在php7裏不能被正確執行。回調函數

 

$content = preg_replace_callback("/{#(.+?)}/is", function($r)use($lang){ return $lang[$r[1]]; }, $content);io

這是改過以後的代碼function

 

須要注意:變量

1. preg_replace_callback第二個參數,callback()函數裏,若是須要使用外部的變量,可使用function callback($matchs)use($xxx){}call

2. callback() 回調函數裏,return 值會替換匹配到的內容callback

相關文章
相關標籤/搜索