<?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);
You have javascript disabled. You will not be able to edit any code.