3v4l.org

run code in 300+ PHP versions simultaneously
<?php $string = 'gamer thing gamer games test games'; $pattern = '/\b(?<keyword>gamer|games)\b/'; // We'll append to this array after we use a given keyword $usedKeywords = []; $finalString = preg_replace_callback( $pattern, // Remember to capture the array by-ref static function (array $matches) use (&$usedKeywords) { $thisKeyword = $matches['keyword']; if (in_array($thisKeyword, $usedKeywords, true)) { return $thisKeyword; } $usedKeywords[] = $thisKeyword; // Do your replacement here return '~'.$thisKeyword.'~'; }, $string ); print_r($finalString);

preferences:
30.78 ms | 406 KiB | 5 Q