Home >Backend Development >PHP Tutorial >php string replacement problem

php string replacement problem

WBOY
WBOYOriginal
2016-09-12 17:44:431263browse

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?

Reply content:

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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn