【发布时间】:2011-12-28 12:20:49
【问题描述】:
所以问题..我已经坚持这个一个月了,所以请任何帮助将不胜感激。
我正在尝试从数组中的单词中突出显示字符串中的单词。我遇到的问题是嵌套标签。
$bold=array();
$bold="tree,apple tree,orange";
$description="orange and apple tree";
例如; the result I want would be this <strong>orange</strong> and <strong>apple tree</strong>, but the result I am getting is this <strong>orange</strong> and <strong>apple <strong>tree</strong></strong>
我已经拼凑了这个,但它不能按预期工作,所以如果我的方法不正确,请随时修改或丢弃。
function highlightWords($text, $words){
foreach ($words as $word){
$word = preg_quote($word);
$word = (str_replace("/","",$word));
$text = preg_replace("/(?!<.*?)(".preg_quote($word,'/').")(?![^<>]*?>)/si",'<strong>\1</strong>', $text);
}
return $text;
}
$description = highlightWords($description, $bold);
【问题讨论】:
-
你给出的输出有什么问题?
-
我想要 apple tree 而不是 apple tree
标签: php preg-replace