代码之家  ›  专栏  ›  技术社区  ›  Schoffelman

在PHP中突出显示搜索词,而不使用regex破坏锚标记

  •  0
  • Schoffelman  · 技术社区  · 15 年前

    我正在一个网站上搜索一些数据库搜索结果,并尝试在返回的结果中突出显示与搜索词匹配的词。下面是我目前为止(在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 permaLink中,返回的结果将把范围插入到href属性中,并破坏锚标记。在我的regex中,是否有任何方法可以从出现在开始和结束HTML标记之间的搜索结果中排除“任何”信息?

    我知道我可以使用strip_tags()函数,只需以纯文本格式输出结果,但如果不必这样做,我宁愿不这样做。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Community CDub    8 年前

    尝试使用正则表达式分析HTML:
    RegEx match open tags except XHTML self-contained tags

    尝试一下 PHP Simple HTML DOM .

    <?php
    // get DOM
    $html = file_get_html('http://www.google.com/search?q=hello+kitty');
    
    // ensure this is properly sanitized.
    $term = trim($term);
    
    // highlight $term in all <div class="result">...</div> elements
    foreach($html->find('div.result') as $e){
       echo str_replace($term, '<span class="highlight">'.$term.'</span>', $e->plaintext);
    }
    ?>
    

    注: 这不是一个 准确的 解决方案是因为我不知道你的HTML是什么样子的,但这应该让你很接近正轨。

        2
  •  0
  •   Ed G    15 年前

    我认为断言是你想要的。

        3
  •  0
  •   Schoffelman    15 年前

    我最终走上了这条路,到目前为止,这条路在这种特定的情况下运行得很好。

    <?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标记更容易解析