Home >Backend Development >PHP Tutorial >php preg_replace replacement example explanation_PHP tutorial
At first glance, I was stunned
Generally, if the matching pattern and replacement content are both arrays, they should correspond. If there are fewer elements in replacement than in pattern , the extra pattern is replaced with an empty string.
$pattern is like a scanner. If it finds a match, it is replaced with the corresponding $replace
For the above example, the replacement process is as follows:
/ d/Scan 1 in $subject, and if it matches, if the matching content is $0 (that is, 1), replace 1 with A:1
, and then use /[a-z]/ to scan A:1 if it does not match, then it will not be replaced. Continue to use [1a] to scan A:1, the matching content is 1 (that is, $0), replace the 1 in A:1 with C:1
The first item is finally replaced with A:C:1
Simplify the process:
1->A:1->A:C:1
a->B:a->B:C:a
2->A:2
b ->B:b
A (If there is no match, it will not be replaced)
B (Same as above)
4->A:4
To summarize, take every item in $pattern The pattern matches each element in $subject in turn. When matched, it is replaced with the $replace corresponding to $pattern. As in the above example,