PHP Preg_replace Replace examples to explain _php tips

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.