Home >Backend Development >PHP Tutorial >php preg_replace replacement example explanation_PHP tutorial

php preg_replace replacement example explanation_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:38847browse

Copy code The code is as follows:

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $ limit = -1 [, int &$count ]] )

is a function that performs search and replacement of a regular expression. Usually when we use it, it usually ends with one replacement. Today we saw it again The PHP manual found a relatively difficult (in my opinion) example to share with you.
Copy code The code is as follows:

$subject = array('1', 'a ', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/d/', '/[a-z]/', ' /[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');

echo "preg_replace returnsn
 ";
print_r(preg_replace($pattern, $replace, $subject));
?>

The result is as follows:

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,

may be replaced more than once.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825007.htmlTechArticleCopy code The code is as follows: mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int lt;?php $subject = array('1', 'a', '2', 'b', '3', 'A'...
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