3v4l.org

run code in 300+ PHP versions simultaneously
<?php $string = "This is a " . str_repeat("test", 2) . "!\n" . str_repeat("hello", 3) . " and Bye!\n" . "When I sleep, the thought bubble says " . str_repeat("zz", 3) . "."; function str_shrink($string, $needles) { $needles = array_map(function($needle) { return preg_quote($needle, '~'); }, $needles); return preg_replace_callback( '~\b(' . implode('|', $needles) . ')\1+\b~', function($m) { return "[{$m[1]}](" . (strlen($m[0]) / strlen($m[1])) . ")"; }, $string ); } echo str_shrink($string, ['test', 'hello']);

preferences:
28.99 ms | 408 KiB | 5 Q