I’m trying to preg_replace()
a string with a different replacement for each found match. Below is an example string and the pattern to look for:
$string = "111111Z not-a-match 000000Z not-a-match 000000Z";
$pattern = "/d{6}Z/";
I want to be able to replace the matches based on the order they were found. For example, replace the first match (‘111111Z’) with ‘FIRST’. Meaning my desired value would be something like:
$newString = "FIRST not-a-match SECOND not-a-match THIRD"
What is the best way to get from $string
to $newString
?
I’ve been looking into setting a $matches
variable in either a preg_match_all()
or a preg_replace_callback()
, and then loop through each match, but I’m struggling to get back around to the full original string with the matches replaced.
4
Answers
One way is
preg_replace_callback()
, using an extra array with the replacements:Output
To solve this, you can use preg_replace_callback() in PHP, which allows you to define a custom function to handle each match. This custom function will keep track of the match order and replace each match with the corresponding value (‘FIRST’, ‘SECOND’, ‘THIRD’, etc.).
You can try this
OUTPUT
Use
preg_replace()
with the replacement limit optional argument, so it only replaces each match once before going to the next element of the pattern and replacement arrays.