突出显示搜索结果 - 整个表达式和单个单词

时间:2013-02-27 23:41:55

标签: php regex preg-replace

我希望突出显示整个表达和单个单词

$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?

1 个答案:

答案 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;

?>