可能重复:
Best way to parse HTML with PHP
PHP Regular expression to match keyword outside HTML tag <a>
我想突出显示要搜索的关键字,并让不替换HTML标记。我使用了这个函数,但它取代了链接(锚标签)。有没有办法突出显示搜索字词,而不会创建无效的HTML。
function highlightSearch($str,$keyword='')
{
// $str=text in which I want to search,$keyword is the word which I want to replace.
$keywords = preg_replace('/\s\s+/i', ' ', strip_tags(trim($keyword)));
foreach(array_unique(explode(' ', $keywords)) as $keyword)
{
//if(!preg_match("|<[^>]+>(.*)</[^>]+>|Ui",$str))
$str = str_ireplace($keyword,"<b>".$keyword."</b>",$str);//preg_replace("|($keyword)|Ui", "<b>$1</b>", $str);
//}
//$str = str_ireplace( "<b>","<b>", $str);`
return $str;
}
}