谷歌喜欢搜索结果

时间:2011-10-30 11:26:13

标签: php str-replace substr strpos

从我的上一个问题引出:

Tidying search results from database php

我的研究让我得到以下代码来截断搜索结果,突出显示关键字并在关键字的左侧和右侧显示多个字符。看起来更好。

现在我的问题是,使用下面的代码,通过在关键字的左侧或右侧添加字符,它会将单词切成两半。

示例:

Savings plans

..le="background: #E13300;">investing in international accounts is no longer the premise of the rich and famous, all expatriates living abroad can now enjoy flex...

如何使截断功能停止将我的单词和标签切成两半????

代码:

 $word = 'invest'; 
$characters_before="80";
$characters_after="80";
function supertruncate($text, $word, $characters_before, $characters_after){
                  $pos = strpos($text, $word);
    $start = $characters_before < $pos ? $pos - $characters_before : 0;
    $len = $pos + strlen($word) + $characters_after - $start;
                   $text = str_ireplace($word, '<span class="highlight" style="background: #E13300;">' . $word . '</span>', $text);
    return substr($text, $start, $len);
}

1 个答案:

答案 0 :(得分:0)

首先截断。然后突出显示。

$text = substr($text, $start, $len);
return str_ireplace($word, '<span class="highlight" style="background: #E13300;">' . $word . '</span>', $text);
相关问题