I am using the below code to truncate my content before and after the first search keyword in my text (this is for my search page) everything works as it should apart from the code cutting words in half at the beginning of the truncate, it doesn’t cut words at the end of the truncate.
Example:
lients at the centre of the relationship and to offer a first class service to them, which includes tax planning, investment management and estate planning. We believe that our customer focused and...
(edit:it is sometimes more than one character missing from the word)
You will see that it has chopped the ‘c’ off ‘clients’. It only happens at the beginning of the text not the end. How can I fix this? I believe I am half way there. code so far:
function neatest_trim($content, $chars, $searchquery,$characters_before,$characters_after) {
if (strlen($content) > $chars) {
$pos = strpos($content, $searchquery);
$start = $characters_before < $pos ? $pos - $characters_before : 0;
$len = $pos + strlen($searchquery) + $characters_after - $start;
$content = str_replace(' ', ' ', $content);
$content = str_replace("\n", '', $content);
$content = strip_tags(trim($content));
$content = preg_replace('/\s+?(\S+)?$/', '', mb_substr($content, $start, $len));
$content = trim($content) . '...';
$content = strip_tags($content);
$content = str_ireplace($searchquery, '<span class="highlight" style="background: #E6E6E6;">' . $searchquery . '</span>', $content);
}
return $content;
}
$results[] = Array(
'text' => neatest_trim($row->content,200,$searchquery,120,80)
);
The 120 Characters that you are keeping at the start don’t check if the 120th character is a space or a letter, and just cuts the string there no matter what.
I would make this change, to search for the closest “space” to the position we are starting from.
This way
$startis the position of a space, and not a letter from a word.Your Function would become: