以下是在PHP 5.2中正常运行的两个函数:
function highlight($text, $words, $prepend) {
$text = str_replace('\"', '"', $text);
foreach($words AS $key => $replaceword) {
$text = str_replace($replaceword, '<highlight>'.$replaceword.'</highlight>', $text);
}
return "$prepend$text";
}
function search_highlight($message, $words, $color = '#ff0000') {
if(!empty($words)) {
$highlightarray = explode(' ', $words);
$sppos = strrpos($message, chr(0).chr(0).chr(0));
if($sppos !== FALSE) {
$specialextra = substr($message, $sppos + 3);
$message = substr($message, 0, $sppos);
}
$message = preg_replace(array("/(^|>)([^<]+)(?=<|$)/sUe", "/<highlight>(.*)<\/highlight>/siU"), array("highlight('\\2', \$highlightarray, '\\1')", "<strong><font color=\"$color\">\\1</font></strong>"), $message);
if($sppos !== FALSE) {
$message = $message.chr(0).chr(0).chr(0).$specialextra;
}
}
return $message;
}
测试功能:
search_highlight("here is the test content","test");
结果,test
将突出显示。
但是在PHP 5.5中,PREG_REPLACE_EVAL
的{{3}}(preg_replace
)已弃用 - 如何将preg_replace
函数替换为preg_replace_callback
?
该行:
$message = preg_replace(array("/(^|>)([^<]+)(?=<|$)/sUe", "/<highlight>(.*)<\/highlight>/siU"), array("highlight('\\2', \$highlightarray, '\\1')", "<strong><font color=\"$color\">\\1</font></strong>"), $message);
到
$message = preg_replace_callback(
$pattern,
$callback,
$message
);
我很困惑怎么做。