dongzan0108 2010-02-18 21:31 采纳率: 0%
浏览 46
已采纳

使用正则表达式突破锚定标记,突出显示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;
}

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?

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.

  • 写回答

3条回答 默认 最新

  • duanoucuo7045 2010-02-19 21:29
    关注

    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('|
    [^<]+|', '</p><p>', $str_content);
        break;
    }
    
    ?>
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图