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"; }
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
..searched the <b>keyword</b> and I need.. <b>keyword</b> at the very.. ..can end with <b>keyword</b> <b>keyword</b>

preferences:
91.73 ms | 407 KiB | 5 Q