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

php string replacement problem

WBOY
Release: 2016-09-12 17:44:43
Original
1278 people have browsed it

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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template