我希望突出显示整个表达和单个单词
$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
foreach ($words as $k=>$v){
$text = preg_replace('/(\w*?'.$v.'\w*)/i', '[b]$1[/b]', $text);
}
此代码将返回:
文字文字[b] [b] aaa [/ b] [b] bbb [/ b] [b] ccc [/ b] [/ b] text [b] aaa [/ b] text [ b] xxaaayy [/ b] text [b] [b] bbb [/ b] [b] ccc [/ b] [/ b] text [b] [b] bbb [/ b] [b] cccxxx [/ b ] [/ b]文字
如何获得此结果:
文本文本[b] aaa bbb ccc [/ b] text [b] aaa [/ b] text [b] xxaaayy [/ b] text [b] bbb ccc [/ b] text [b] bbb cccxxx [/ b] text
如何修改preg_replace?
答案 0 :(得分:1)
你去了:
<?php
$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
$text = preg_replace('/('.implode("|",$words).')/i', '[b]$1[/b]', $text);
echo $text;
?>
更新版本:
<?php
$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text";
$words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc');
$text = preg_replace('/(\w*('.implode("|",$words).')\w*)/i', '[b]$1[/b]', $text);
echo $text;
?>