突出显示搜索词
我有一个情况,我正在返回数据库结果并根据搜索词将它们显示在页面上。 这部分工作正常,但我想通过将这些搜索词包装在 span 标签中来突出显示它们。 我开始编写一个函数,对每个使用 str_replace 函数的结果进行调用,但后来我意识到这也会影响 HTML 标记中的任何文本。 有人有他们用来有效地做到这一点的功能吗? 我正在使用 PHP 4。 谢谢!
I have a case where I'm returning database results and displaying them on a page based on a search term. This part is working fine, but I want to hightlight these search terms by wrapping them in span tags. I started to write a function that I called on each result that used the str_replace function, but then it dawned on me that this would also affect any text that is in HTML tags. Does anybody have a function they use to do this effectively? I'm using PHP 4.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会用 javascript
http: //johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
这样你就不会弄乱源代码,用户可以根据需要转动突出显示,等等。
I'd go for highlight with javascript
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
this way you don't mess with the source, user can turn highlight if you want, etc.
我曾经用 Perl 编写过一个搜索,是这样的(对 PHP 做了一些翻译):
如果满足以下条件,则可以避免使用正则表达式:
没有测试它,但应该是这样的。
I've once written a search in Perl, did it like this (did a little translation to PHP):
You could avoid using Regular Expressions if:
Did not test it, but should be something like this.
如果您返回结果并显示它们,那么您不应该在原始数据以 html 形式生成之前访问它吗? 如果是这样,则通过在其中添加 span 标签来对原始数据进行修改。
如果您说您的原始数据可能已经包含 html,那么您可以使用正则表达式来检测您是否位于 html 标记内,并使用 preg_replace 而不是 str_replace。
其他选项:
-- 将结果加载到 dom 解析器中,并且只在叶文本节点上执行替换操作
-- 编写您自己的解析器来跟踪您是否在 html 标签内
-- 从您的 HTML 标签中取出所有 HTML 标签结果,放入占位符,例如
" [[[tag1]]] balha blah blah [[[tag2]]]" 然后对剩余文本进行替换,然后将标签替换回
If you are returning the results and displaying them, then shouldn't you have access to the raw data before it gets churned out in html? If so, then do your modifying on the raw data by adding the span tags in there.
If you are saying that your raw data may already have html in it, you may be able to use a regex to detect whether you are inside an html tag, and use preg_replace instead of str_replace.
Other options:
--load results into a dom parser and only do replace operations on the leaf text nodes
-- write your own parser to keep track of if you are inside an html tag or not
-- yank out all the HTML tags from your results, put in placeholders like
" [[[tag1]]] balha blah blah [[[tag2]]]" then do your replace on the remaining text, then substitute your tags back in