突出显示单词末尾的单词
我不确定如何更好地表达标题,但我的问题是突出显示功能不会突出显示单词末尾的搜索关键字。例如,如果搜索关键字是“self”,则会突出显示“self”或“self-less”或“Self”[大写S],但不会突出显示“yourself”或“himself”等自我。 。
这是突出显示的功能:
function highlightWords($text, $words) {
preg_match_all('~\w+~', $words, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')~i';
$string = preg_replace($re, '<span class="highlight">$0</span>', $text);
return $string;
}
i'm not sure how i could have phrased the title better, but my issue is that the highlight function doesn't highlight the search keywords which are at the end of the word. for example, if the search keyword is 'self', it will highlight 'self' or 'self-lessness' or 'Self' [with capital S] but it will not highlight the self of 'yourself' or 'himself' etc. .
this is the highlight function:
function highlightWords($text, $words) {
preg_match_all('~\w+~', $words, $m);
if(!$m)
return $text;
$re = '~\\b(' . implode('|', $m[0]) . ')~i';
$string = preg_replace($re, '<span class="highlight">$0</span>', $text);
return $string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来您的正则表达式开头可能有一个
\b
,这意味着单词边界。由于“yourself”中的“self”不是从单词边界开始,因此它不匹配。去掉\b
。It seems you might have a
\b
at the beginning of your regex, which means a word boundary. Since the 'self' in 'yourself' doesn't start at a word boundary, it doesn't match. Get rid of the\b
.尝试这样的事情:
循环是为了正确引用每个搜索词...
编辑:修改函数以在
$words
参数中采用字符串或数组。Try something like this:
The loop, is so that every search word is properly quoted...
EDIT: Modified function to take either string or array in
$words
parameter.