在PHP中突出显示搜索条件,而不使用正则表达式打破锚定标记 [英] Highlight Search Terms in PHP without breaking anchor tags using regex

查看:89
本文介绍了在PHP中突出显示搜索条件,而不使用正则表达式打破锚定标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过网站上的一些数据库搜索结果进行搜索,试图在与搜索到的词相匹配的返回结果中突出显示该词。下面是我到目前为止(在PHP中):

I'm searching through some database search results on a website & trying to highlight the term in the returned results that matches the searched term. Below is what I have so far (in php):

$highlight = trim($highlight);
if(preg_match('|\b(' . $highlight . ')\b|i', $str_content))
{
    $str_content = preg_replace('|\b(' . $highlight. ')(?!["\'])|i', "<span class=\"highlight\">$1</span>", 
    $str_break;
}

这条路线的缺点是,如果我的搜索字词显示在url永久链接,以及返回的结果将跨度插入到href属性,并打破锚标记。是否有反正在我的正则表达式排除任何信息从搜索结果中出现在开幕式和闭幕式之间的HTML标签?

The downside of going this route is that if my search term shows up in the url permalink as well, the returned result will insert the span into the href attribute and break the anchor tag. Is there anyway in my regex to exclude "any" information from the search results that appear in between an opening and closing HTML tag?

我知道我可以使用strip_tags()函数,并以纯文本的形式吐出结果,但如果没有,我宁愿不这样做必须。

I know I could use the strip_tags() function and just spit out the results in plain text, but I'd rather not do that if I didn't have to.

推荐答案

我最终选择了这条路线,目前为止,这种路线对于这种特殊情况非常有效。

I ended up going this route, which so far, works well for this specific situation.

<?php

if(preg_match('|\b(' . $term . ')\b|i', $str_content))
{
    $str_content = strip_tags($str_content);
    $str_content = preg_replace('|\b(' . $term . ')(?!["\'])|i', "<span class=\"highlight\">$1</span>", $str_content);
    $str_content = preg_replace('|\n[^<]+|', '</p><p>', $str_content);
    break;
}

?>

它仍然是html编码的,但现在无需html标签即可轻松解析。

It's still html encoded, but it's easier to parse through now without html tags

这篇关于在PHP中突出显示搜索条件,而不使用正则表达式打破锚定标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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