<?php
$texts = [
"For example this is the text where I searched the keyword and I need the text around it too.",
"keyword at the very start",
"Or it can end with keyword",
"Nothing to see here officer.",
"keyword",
];
$needle = "keyword";
$extra = 10;
foreach ($texts as $text) {
$new = preg_replace_callback(
"/.*?(\S+.{0,$extra})?($needle)(.{0,$extra}\S+)?.*/",
function($m) {
return sprintf(
'%s<b>%s</b>%s',
strlen($m[1]) ? "..{$m[1]}" : '',
$m[2],
strlen($m[3] ?? '') ? "{$m[3]}.." : ''
);
},
$text,
1,
$count
);
echo ($count ? $new : '') . "\n";
}