突出显示字符串中的单词(如果包含关键字) [英] highlight the word in the string, if it contains the keyword

查看:127
本文介绍了突出显示字符串中的单词(如果包含关键字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果包含关键字,如何编写整个单词的脚本? 示例:关键字"fun",字符串-鸟很有趣,结果-鸟很有趣*.我执行以下操作

how write the script, which menchion the whole word, if it contain the keyword? example: keyword "fun", string - the bird is funny, result - the bird is * funny*. i do the following

     $str = "my bird is funny";
     $keyword = "fun";
     $str = preg_replace("/($keyword)/i","<b>$1</b>",$str);

但仅修饰关键字.我的鸟是好玩 ny

but it menshions only keyword. my bird is funny

推荐答案

尝试一下:

preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str)

\w*?匹配关键字之前的任何单词字符(至少),并且\w*匹配关键字之后的任何单词字符.

\w*? matches any word characters before the keyword (as least as possible) and \w* any word characters after the keyword.

而且我建议您使用 preg_quote 来避开关键字:

And I recommend you to use preg_quote to escape the keyword:

preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str)

要获得Unicode支持,请使用 u 标志和\p{L}而不是\w:

For Unicode support, use the u flag and \p{L} instead of \w:

preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b>$0</b>", $str)

这篇关于突出显示字符串中的单词(如果包含关键字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆