Arj*_*jen 6 php regex preg-replace
我正在使用下面的代码突出显示文本中的一些关键字:
$message = str_ireplace($words,'<span class="hightlighted_text">'.$words.'</span>',$message);
Run Code Online (Sandbox Code Playgroud)
文本可能包含某些HTML标记,例如<img>
,<strong>
等.
除了html标签之间的文字外,如何突出显示"普通"文字?因为当用户搜索"img"时,<img>
文本将突出显示,图像不再起作用.
来自http://forum.phpfrance.com/vos-contributions/remplacement-selectif-hors-dans-balises-html-t199.html
function mon_rplc_callback($capture){
global $arg;
return ($arg['flag'] == 1)
? $arg['fct']($arg['from'], $arg['to'], $capture[1]).$capture[2]
: $capture[1].$arg['fct']($arg['from'], $arg['to'], $capture[2]);
}
function split_tag($from, $to, $txt, $fct, $flag = 1){
global $arg;
$arg = compact('from', 'to', 'fct', 'flag');
return preg_replace_callback('#((?:(?!<[/a-z]).)*)([^>]*>|$)#si', "mon_rplc_callback", $txt);
}
Run Code Online (Sandbox Code Playgroud)
当 $flag == 1 时,替换函数在 HTML 外部应用。当 $flag == -1 时,替换函数将应用于 HTML 内部。
应用于您的示例,它将给出如下内容:
echo split_tag($words, '<span class="hightlighted_text">'.$words.'</span>', $message, 'str_ireplace', 1);
Run Code Online (Sandbox Code Playgroud)
享受!;)