【发布时间】:2012-01-23 18:35:56
【问题描述】:
我有一个 PHP 高亮功能,可以使某些单词变粗。
下面是这个函数,它工作得很好,除非数组:$words 包含一个值,即:b
例如有人搜索:jessie j price tag feat b o b
这将在数组 $words 中包含以下条目:jessie,j,price,tag,feat,b,o,b
当出现“b”时,我的整个函数都会出错,并且会显示一大堆错误的 html 标签。当然,我可以从数组中删除任何 'b' 值,但这并不理想,因为突出显示在某些查询中无法正常工作。
这个示例脚本:
function highlightWords2($text, $words)
{
$text = ($text);
foreach ($words as $word)
{
$word = preg_quote($word);
$text = preg_replace("/\b($word)\b/i", '<b>$1</b>', $text);
}
return $text;
}
$string = 'jessie j price tag feat b o b';
$words = array('jessie','tag','b','o','b');
echo highlightWords2($string, $words);
将输出:
<<<b>b</b>><b>b</b></<b>b</b>>>jessie</<<b>b</b>><b>b</b></<b>b</b>>> j price <<<b>b</b>><b>b</b></<b>b</b>>>tag</<<b>b</b>><b>b</b></<b>b</b>>> feat <<b>b</b>><b>b</b></<b>b</b>> <<b>b</b>>o</<b>b</b>> <<b>b</b>><b>b</b></<b>b</b>>
这只是因为数组中有“b”。
你们能看到我可以改变什么以使其正常工作吗?
【问题讨论】:
-
你在哪里找到这个函数的?
-
我在网上找到了它,但实际上我刚刚解决了我的问题。如果我将 和 更改为 和 ,那么它可以完美运行。 preg_replace 中的 \b 一定是在使用 和 标签。
-
这是一种解决方法,直到
strong成为搜索词。 -
<i>carport</i>或<i>car</i>port中是否也需要突出显示 carport 之类的词?