【发布时间】:2014-06-10 12:43:36
【问题描述】:
我正在尝试突出显示 $vQuery 中的确切术语,目前如果 $vQuery 是单词的一部分,它将突出显示整个单词。我不能使用 str_replace 或 str_ireplace,因为需要显示的内容和替换的内容之间存在大小写问题,所以我留下了一个使用 preg_replace 的过于复杂的语句。
preg_replace("/\b".$vQuery."\b/i", "<span class=\"highlightedTerm\">$0</span>", $vName);
上述语句将按预期匹配,但假设我搜索car,它将突出显示所有单词car,但也会突出显示包含car 的任何内容。
有没有一种简单的方法可以修改模式以使其完全匹配?!
编辑:
说我有:
This is the carpet in my car.
我希望有这样的输出:
This is the <span class="highlightedTerm">car</div>pet in my <span class="highlightedTerm">car</div>.
目前,我得到的是:
This is the <span class="highlightedTerm">carpet</div> in my <span class="highlightedTerm">car</div>.
希望它更清楚。
【问题讨论】:
-
它应该只匹配“全词”汽车,因为你使用了boundry这个词:regex101.com/r/jU1vV9
-
我已经用更多信息更新了问题,以使我的问题更清楚。
-
放弃
\bs regex101.com/r/hZ4zB6 一个好的建议是做一个正则表达式教程来了解元字符、锚点等的含义。
标签: php preg-replace