突出显示段落中的关键字

dol*_*ole 2 php string search

我需要在一个段落中突出显示关键字,就像Google在搜索结果中所做的那样.我们假设我有一个带有博客文章的MySQL数据库.当用户搜索某个关键字时,我希望返回包含这些关键字的帖子,但只显示部分帖子(包含搜索关键字的段落)并突出显示这些关键字.

我的计划是这样的:

  • 找到在其内容中包含搜索关键字的帖子ID;
  • 再次读取该帖子的内容并将每个单词放在一个固定的缓冲区数组(50个单词)中,直到找到该关键字.

你能帮助我一些逻辑,或者至少告诉我我的逻辑是否合适?我正处于PHP学习阶段.

irc*_*ell 9

如果它包含html(请注意,这是一个非常强大的解决方案):

$string = '<p>foo<b>bar</b></p>';
$keyword = 'foo';
$dom = new DomDocument();
$dom->loadHtml($string);
$xpath = new DomXpath($dom);
$elements = $xpath->query('//*[contains(.,"'.$keyword.'")]');
foreach ($elements as $element) {
    foreach ($element->childNodes as $child) {
        if (!$child instanceof DomText) continue;
        $fragment = $dom->createDocumentFragment();
        $text = $child->textContent;
        $stubs = array();
        while (($pos = stripos($text, $keyword)) !== false) {
            $fragment->appendChild(new DomText(substr($text, 0, $pos)));
            $word = substr($text, $pos, strlen($keyword));
            $highlight = $dom->createElement('span');
            $highlight->appendChild(new DomText($word));
            $highlight->setAttribute('class', 'highlight');
            $fragment->appendChild($highlight);
            $text = substr($text, $pos + strlen($keyword));
        }
        if (!empty($text)) $fragment->appendChild(new DomText($text));
        $element->replaceChild($fragment, $child);
    }
}
$string = $dom->saveXml($dom->getElementsByTagName('body')->item(0)->firstChild);
Run Code Online (Sandbox Code Playgroud)

结果是:

<p><span class="highlight">foo</span><b>bar</b></p>
Run Code Online (Sandbox Code Playgroud)

与:

$string = '<body><p>foobarbaz<b>bar</b></p></body>';
$keyword = 'bar';
Run Code Online (Sandbox Code Playgroud)

你得到(分为多行以便于阅读):

<p>foo
    <span class="highlight">bar</span>
    baz
    <b>
        <span class="highlight">bar</span>
    </b>
</p>
Run Code Online (Sandbox Code Playgroud)

谨防非dom解决方案(如regexstr_replace),因为突出显示类似"div"的东西有完全破坏你的HTML的倾向......这只会"突出"身体中的字符串,永远不会在标签内...


编辑因为您需要Google样式结果,所以这是一种方法:

function getKeywordStubs($string, array $keywords, $maxStubSize = 10) {
    $dom = new DomDocument();
    $dom->loadHtml($string);
    $xpath = new DomXpath($dom);
    $results = array();
    $maxStubHalf = ceil($maxStubSize / 2);
    foreach ($keywords as $keyword) {
        $elements = $xpath->query('//*[contains(.,"'.$keyword.'")]');
        $replace = '<span class="highlight">'.$keyword.'</span>';
        foreach ($elements as $element) {
            $stub = $element->textContent;
            $regex = '#^.*?((\w*\W*){'.
                 $maxStubHalf.'})('.
                 preg_quote($keyword, '#').
                 ')((\w*\W*){'.
                 $maxStubHalf.'}).*?$#ims';
            preg_match($regex, $stub, $match);
            var_dump($regex, $match);
            $stub = preg_replace($regex, '\\1\\3\\4', $stub);
            $stub = str_ireplace($keyword, $replace, $stub);
            $results[] = $stub;
        }
    }
    $results = array_unique($results);
    return $results;
}
Run Code Online (Sandbox Code Playgroud)

好的,那么它的作用是返回一个带有$maxStubSize它周围单词的匹配数组(即之前的数字的一半,之后的一半)......

所以,给定一个字符串:

<p>a whole 
    <b>bunch of</b> text 
    <a>here for</a> 
    us to foo bar baz replace out from this string
    <b>bar</b>
</p>
Run Code Online (Sandbox Code Playgroud)

通话getKeywordStubs($string, array('bar', 'bunch'))将导致:

array(4) {
  [0]=>
  string(75) "here for us to foo <span class="highlight">bar</span> baz replace out from "
  [3]=>
  string(34) "<span class="highlight">bar</span>"
  [4]=>
  string(62) "a whole <span class="highlight">bunch</span> of text here for "
  [7]=>
  string(39) "<span class="highlight">bunch</span> of"
}
Run Code Online (Sandbox Code Playgroud)

那么,你可以通过对列表进行排序strlen然后选择两个最长的匹配来构建你的结果模糊...(假设php 5.3+):

usort($results, function($str1, $str2) { 
    return strlen($str2) - strlen($str1);
});
$description = implode('...', array_slice($results, 0, 2));
Run Code Online (Sandbox Code Playgroud)

结果如下:

here for us to foo <span class="highlight">bar</span> baz replace out...a whole <span class="highlight">bunch</span> of text here for 
Run Code Online (Sandbox Code Playgroud)

我希望有所帮助......(我觉得这有点......臃肿......我确信有更好的方法可以做到这一点,但这是一种方式)......