На всякий случай, нормальный ответ
/**
* @param string $text
* @param string $key
* @param int $wordsCount
* @return array
*/
public static function extractMatches($text, $key, $wordsCount = 10)
{
$quote = preg_quote($key);
$regex = '/(?:[^ ]+ ){0,'.$wordsCount.'}[\p{L}\p{Nd}-\.]*('.$quote.')[\p{L}\p{Nd}-\.]*(?: [^ ]+){0,'.$wordsCount.'}/iu';
$matches = [];
preg_match_all($regex, $text, $matches);
return count($matches[0]) > 0 ? $matches[0] : [];
}
/**
* @param string $text
* @param string $key
* @param string $template
* @return array
*/
public static function highlight($text, $key, $template = '<i>\1</i>')
{
$fragments = [];
$matches = self::extractMatches($text, $key);
$quote = preg_quote($key);
foreach ($matches as $match) {
$fragments []= preg_replace("/($quote)/i", $template, $match);
}
return $fragments;
}