I’m building a custom search result in php where I want to return n characters from left and right of the searched keyword. I would also like to preserve whole words at the beginning and the end.
For example this is the text where I searched the keyword and I
need the text around it too.
So if I say n characters is 10 I would preferably get:
..searched the keyword and I need..
A simpler acceptable solution would be to break the words so the result would be:
..rched the keyword and I nee..
I started with this but got stuck on the string part before the keyword:
private function getSubstring($content,$keyword, $nOfChars) {
$content = strtolower(strip_tags($content));
$noOffoundStrings = substr_count($content, $keyword);
$position = strpos($content, $keyword);
$keywordLength = strlen($keyword);
$afterKey = substr($content, $position + $keywordLength, $nOfChars);
$beforeKey = substr($content, $position , -???); // how to get string part before the searched keyword
}