如果包含或匹配搜索词,则将整个单词和单个字符包含在 HTML 标记中
我想将 HTML 标签添加到包含搜索词的单词中,并且我想在每次出现的搜索词周围添加嵌套标签。
示例字符串:
$str = "i like programming very much";
示例搜索词:
$word = "r";
所需结果:
i like <span class='pice1'>p<span class='pice2'>r</span>og<span class='pice2'>r</span>aming</span> <span class='pice1'>ve<span class='pice2'>r</span>y</span> much
我为其编写了以下正则表达式,但有时不起作用。
$str = preg_replace(
"/([^\s{" . preg_quote($word) . "}]*?)(" . preg_quote($word) . ")([^\s{" . preg_quote($word) . "}]*)/siu",
"<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",
$str
);
I want to add HTML tags to words that contain a search term AND I want to add nested tags around each occurrence of the search term.
Sample string:
$str = "i like programming very much";
Sample search term:
$word = "r";
Desired result:
i like <span class='pice1'>p<span class='pice2'>r</span>og<span class='pice2'>r</span>aming</span> <span class='pice1'>ve<span class='pice2'>r</span>y</span> much
I wrote the following regex for it, but it sometimes doesn't work.
$str = preg_replace(
"/([^\s{" . preg_quote($word) . "}]*?)(" . preg_quote($word) . ")([^\s{" . preg_quote($word) . "}]*)/siu",
"<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",
$str
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不直接使用 str_replace() 呢?我认为这更简单
Why dont't you just use str_replace()? I think it's more simple
输出:
回答评论:分两步完成。
输出:
Output:
Answer to the comment: do it in two steps.
output:
这种方式怎么样:
What about this way :
完成这项工作(它也适用于外语)...
do the job(and it works with foreign languages too)...
要将包含搜索词的整个单词包装在给定 HTML 标记中,请使用
preg_replace_callback()
并使正则表达式模式不区分大小写且以 unicode 安全方式匹配搜索词前后的零个或多个单词字符。隔离整个单词后,再次搜索该搜索词,并用另一个 HTML 标签包裹每个出现的位置。
str_replace()
不适合这种内部替换,因为它不会保留匹配搜索词的大小写。代码:(演示)
原始输出:
渲染的 HTML
To wrap whole words which contain the search term in a given HTML tag, use
preg_replace_callback()
and have the regex pattern case-insensitively and unicode-safely match zero or more word character before and after the search term.Once the whole word is isolated, search for the search term again and wrap each occurrence with another HTML tag.
str_replace()
is not suitable for this inner replacement because it will not preserve the case of the matched search term.Code: (Demo)
Raw Output:
Rendered HTML