在PHP 5.5中将preg_replace替换为preg_replace_callback函数

时间:2014-05-27 03:50:16

标签: php preg-replace-callback

以下是在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
);

我很困惑怎么做。

0 个答案:

没有答案