How would I got about replacing this
Lorem ipsum random_5ac18d179707d dolor random_5ac18d179707d sit amet, consectetur random_5ac18decebd4e adipiscing elit.
with this
Lorem ipsum random_1 dolor random_1 sit amet, consectetur random_2 adipiscing elit.
What it's doing is matching all "random_xxxxxxxxxxxxx" that are the same and giving that set of like matches a count of 1. The count then gets incremented for each additional set of like matches. There could be one or many in each set.
I have the following that is very close but just not quite right:
function replace($string) {
$i = 1;
return preg_replace_callback('/random_\w+/', function () use (&$i) {
return 'random_' . $i++;
}, $string);
}
which outputs the following
Lorem ipsum random_1 dolor random_2 sit amet, consectetur random_3 adipiscing elit.
Any way to tweak that snippet above to work?
Or perhaps there's some way to get an array of unique matches using preg_match which could then be looped and replaced with a counter? Something similar to so:
$string = 'Lorem ipsum random_5ac18d179707d dolor random_5ac18d179707d sit amet, consectetur random_5ac18decebd4e adipiscing elit.';
preg_match('/random_\w+/', $string, $matches);
print_r($matches);
# to get the following array if possible?
Array
(
[0] => random_5ac18d179707d
[1] => random_5ac18decebd4e
)