【问题标题】:php - problem with displaying text around a search termphp - 在搜索词周围显示文本的问题
【发布时间】:2010-10-19 18:22:14
【问题描述】:

我在 Best practices on displaying search results with associated text snippets from actual result 的 stackoverflow 上找到了这段代码

但是它并不能完全满足我的要求。它显示给定搜索词周围的文本,但有两个问题

1) 我只想要整个单词; 2) 它不限制搜索词之后的字符,只限制搜索词之前的字符

这是下面的代码。如何编辑它以解决这两个问题?提前致谢:

$text = 'This is an example text page with content. It could be red, green or blue or some other random color. It dont really matter.';
$keyword = 'red'; 
$size = 15; // size of snippet either side of keyword
$snippet = '...'.substr($text, strpos($text, $keyword) - $size, strpos($text, $keyword) + sizeof($keyword) + $size).'...'; 
$snippet = str_replace($keyword, '<strong>'.$keyword.'</strong>', $snippet); 
echo $snippet; 

【问题讨论】:

    标签: php


    【解决方案1】:
    $snippet = preg_replace(
        '/^.*?\s(.{0,'.$size.'})(\b'.$keyword.'\b)(.{0,'.$size.'})\s.*?$/',
        '...$1<strong>$2</strong>$3...',
        $text
    );
    

    这将产生:...It could be &lt;strong&gt;red&lt;/strong&gt;, green or blue...\s 字符类将 15 个字符限制为一个分词后出现。

    【讨论】:

      【解决方案2】:

      我在这里发了一个帖子: How to generate excerpt with most searched words in PHP?

      我写过的最混乱的代码可能对你有用。我真的鼓励您排除我在其中的大部分重复代码。

      【讨论】:

        猜你喜欢
        • 2012-08-26
        • 1970-01-01
        • 2011-02-09
        • 2010-10-11
        • 1970-01-01
        • 2012-10-15
        • 1970-01-01
        • 2014-02-13
        • 1970-01-01
        相关资源
        最近更新 更多