Copy Code code as follows:
Mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit =-1 [, int & $count]])
is to perform a regular expression of the search and replace the function, usually we use it when more than a replacement end, today and see the PHP manual found a more difficult to understand (since think) of the example to share.
Copy Code code as follows:
<?php
$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 returns\n<pre/>";
Print_r (Preg_replace ($pattern, $replace, $subject));
?>
The results are as follows:
Look, I'm dizzy.
In general, if both the matching pattern and the replacement content are arrays, they should correspond, and if the elements in the replacement are less than the patterns, then the extra patterning is replaced with an empty string.
$pattern like a scanner, sweep to match the corresponding $replace replacement
For the previous example, the replacement process is as follows:
/\d/Scan $subject 1, match, match the content of $ (that is, 1) to replace 1 with a:1
Then use/[a-z]/scan a:1 do not match, do not replace, continue to use [1a] scan a:1, matching content of 1 (that is, $), put a:1 1 for c:1
The first item is eventually replaced by the A:c:1
Streamline process:
1->a:1->a:c:1
A->b:a->b:c:a
2->a:2
B->b:b
A (no match will not be replaced)
B (IBID.)
4->a:4
To sum up, take $pattern each of the patterns in order to match each element in $subject, matching to the $pattern corresponding to the $replace exchange, as in the example, may be replaced more than once