不区分大小写匹配文本中的多个搜索词并将它们包装在 中HTML 标签
我正在尝试在我正在制作的搜索脚本中将搜索词加粗。问题是我无法让它不区分大小写地工作。
function highlight($term,$target){
$terms = explode(" ", $term);
foreach($terms as $term){
$result = (eregi_replace($term, "<strong>$term</strong>", $target));
}
return $result;
}
这就是我到目前为止所拥有的功能。 PHP.net 上说 eregi_replace()
不区分大小写,但由于某种原因它显然不起作用。
I'm trying to make search terms bold in this search script that I'm making. The trouble is that I can't get it to work case insensitively.
function highlight($term,$target){
$terms = explode(" ", $term);
foreach($terms as $term){
$result = (eregi_replace($term, "<strong>$term</strong>", $target));
}
return $result;
}
That is the function I have so far. It says on PHP.net that eregi_replace()
is case-insensitive, but it's obviously not working for some reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ereg_*
(POSIX 正则表达式)函数已弃用< /a> 从 PHP 5.3 开始,已经很长时间没有被建议了。最好使用 PCRE (preg_*)函数(例如
preg_replace
)。您可以通过创建不区分大小写的正则表达式,然后将匹配项包装在
标记中来实现此目的:
它的作用是首先调用
preg_quote
放在您的$term
上,这样如果有任何字符在该术语的正则表达式中具有含义的术语,它们会被转义,然后创建一个正则表达式来查找由单词边界包围的该术语(\b
- 因此,如果该术语是“好”它不会匹配“再见”)。该术语包含在括号中,以使正则表达式引擎以其现有形式捕获该术语作为“反向引用”(正则表达式引擎挂起匹配部分的一种方式)。通过指定i
选项,表达式不区分大小写。最后,它用标记包围的相同反向引用替换所有匹配项。
如果您想要有关正则表达式的优秀教程,请查看 regular-expressions.info< 上的教程< /a>.
The
ereg_*
(POSIX regular expression) functions are deprecated as of PHP 5.3 and have not been suggested for a long time. It is better to use the PCRE (preg_*
) functions (such aspreg_replace
).You can do so by creating a case-insensitive regular expression, and then wrapping matches in
<strong>
tags:What this does is first call
preg_quote
on your$term
so that if there are any characters that have meaning in a regular expression in the term, they are escaped, then creates a regular expression that looks for that term surrounded by word boundaries (\b
-- so that if the term is "good" it won't match "goodbye"). The term is wrapped in parentheses to make the regular expression engine capture the term in its existing form as a "backreference" (a way for the regular expression engine to hang on to parts of a match). The expression is made case-insensitive by specifying thei
option. Finally, it replaces any matches with that same backreference surrounded by the<strong>
tag.If you'd like a good tutorial on regular expressions, check out the tutorial on regular-expressions.info.
构建一个尊重单词边界的动态、不区分大小写的正则表达式模式,然后将所有替换内容包装在强标签中。
代码:(Demo)
输出:
与 Daniel 的脚本相比,我的脚本始终只对输入进行一次传递string 进行替换,这意味着它将:
Build a dynamic, case-insensitive regex pattern that respects word boundaries, then wrap all replacements in strong tags.
Code: (Demo)
Output:
In comparison to Daniel's script, my script will always only make one pass over the input string to make replacements which means it will: