从我的上一个问题开始:
整理数据库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);
}
先截断。然后亮点。
$text = substr($text, $start, $len);
return str_ireplace($word, '<span class="highlight" style="background: #E13300;">' . $word . '</span>', $text);