3v4l.org

run code in 300+ PHP versions simultaneously
<?php function cutMessage($text, $search) { $pieces = explode(' ', $text); $firstWord = $pieces[0]; $lastWord = array_pop($pieces); $pattern = "/((?:\w+\W+){0,5})" . preg_quote($search, "/") . "((?:\W+\w+){0,5})([!.]?)/"; preg_match($pattern, $text, $matches); $returnText = ''; $pieces = explode(' ', $matches[1]); if (!empty($matches[1]) && $pieces[0] != $firstWord) { $returnText .= '... ' . $matches[1]; } elseif (!empty($matches[1])) { $returnText .= $matches[1]; } $returnText .= $search; $pieces = explode(' ', $matches[2]); if (!empty($matches[3])) { $returnText .= $matches[2] . $matches[3]; } elseif (!empty($matches[2]) && array_pop($pieces) != $lastWord) { $returnText .= $matches[2] . ' ...'; } elseif (!empty($matches[2])) { $returnText .= $matches[2]; } return $returnText; } $texts = [ "Lorem ipsum dolor sit amet, consectetur {query:ABCD:1234} adipiscing elit. Mauris consequat, quam id feugiat varius.", "{query:ABCD:1234} Lorem ipsum dolor sit amet!", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris consequat, quam id feugiat varius {query:ABCD:1234}.", "Lorem ipsum dolor sit amet {query:ABCD:1234} adipiscing elit. Mauris consequat, quam id feugiat varius.", ]; foreach ($texts as $text) { $res = cutMessage($text, "{query:ABCD:1234}"); echo $res . PHP_EOL; }

preferences:
41.41 ms | 402 KiB | 5 Q