preg_replace function can match and replace according to a regular expression, and the number of times can be specified. Now I have a requirement like this. I want to replace the nth time of the specified match, such as a string. I wrote a regular expression, this The string can match a total of three places, and then I only want to replace the second match. What should I do? Is there such an implementation in php?
preg_replace function can match and replace according to a regular expression, and the number of times can be specified. Now I have a requirement like this. I want to replace the nth time of the specified match, such as a string. I wrote a regular expression, this The string can match a total of three places, and then I only want to replace the second match. What should I do? Is there such an implementation in php?
Use preg_replace_callback
Please refer to the manual for usage
You can use preg_replace_callback
to handle it. It calls other functions to handle replacement. You can handle the replacement logic yourself
Just go to the code:
<code>$i=1; $result = preg_replace_callback('/a/',function($match)use(&$i){ $match = $i != 2 ? $match[0] : ''; $i++; return $match; },'a1a2a3a4'); var_dump($result);</code>