3v4l.org

run code in 300+ PHP versions simultaneously
<?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"; }

preferences:
24.58 ms | 405 KiB | 5 Q