Leading on from my last question:
Tidying search results from database php
My research has led me to the following code to truncate search results, highlight the keyword and display a number of characters to the left and right of the keyword. Looking better.
My question now is, with the below code, by adding characters to the left or right of the keyword it is cutting words in half.
example:
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...
How can I make the truncate function stop cutting my words and tags in half????
Code:
$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);
}