php,突出显示搜索关键字而不破坏锚标记
我已经在 Google 和 Stackoverflow 上进行了搜索,但找不到任何适合我的解决方案。
这就是我到目前为止所拥有的:
$string = preg_replace('/'.$keyword.'/i',
'<span class="highlight">$0</span>', $string);
效果很好,除非字符串包含锚标记。但我仍然希望能够突出显示锚标记外部和内部的关键字。
示例:
$keyword = 's';
输出:
我已经在 Google 和 Stackoverflow,但我找不到任何适合我的解决方案。
如果有人能够找到解决方案,而无需使用 PHP Simple HTML DOM Parser,我将不胜感激。
I already did a search on Google and Stackoverflow, but I couldn't find any solution that works for me.
This is what I have so far:
$string = preg_replace('/'.$keyword.'/i',
'<span class="highlight">$0</span>', $string);
Which works fine, except when the string contains anchor tags. But I still want to be able to highlight the keywords outside and within the anchor tags.
Example:
$keyword = 's';
Output:
I alrady did a search on Google and Stackoverflow, but I couldn't find any solution that works for me.
I would appreciate it if someone could find a solution for this without having to use PHP Simple HTML DOM Parser.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该适用于大多数情况:
This should work in most situations:
在我看来,您需要使用 DOM 解析器,因为您只想处理字符串中的“文本”,而不是整个字符串。因此,您需要一种方法来确定什么是“文本”以及什么是 HTML 属性。
有很多示例说明了为什么正则表达式无法解析 HTML。
It seems to me like you'll need to use a DOM parser as you are only wanting to deal with the "text" in your string, rather than the entire string. So you need a way to determine what is "text" and what are HTML attributes.
There are lots of examples of why regex doesn't work for trying to parse HTML.