Interpretation of PHP function preg_replace () array replacement code example

Source: Internet
Author: User

PHP function preg_replace () prototype: mixed preg_replace (mixed $ pattern, mixed $ replacement, mixed $ subject [, int $ limit])

The PHP function preg_replace () is more powerful than c. Arrays can be used for the first three parameters. The fourth parameter $ limit can be used to set the number of replicas. By default, all replicas are replaced. Code 6.7 is an array replacement application instance.

PHP function preg_replace () code 6.7 array replacement

 
  1. <? Php
  2. // String
  3. $ String = "Name: {Name} <br> nEmail:
    {Email} <br> nAddress: {Address} <br> n ";
  4. // Mode
  5. $ Patterns = array (
  6. "/{Address }/",
  7. "/{Name }/",
  8. "/{Email }/"
  9. );
  10. // Replace the string
  11. $ Replacements = array (
  12. "No. 5, Wilson St., New York, U. S. ",
  13. "Thomas Ching ",
  14. "Tom@emailaddress.com ",
  15. );
  16. // Output mode replacement result
  17. Print preg_replace ($ patterns,
    $ Replacements, $ string );
  18. ?>

The output result is as follows.

Name: Thomas Ching ",
Email: tom@emailaddress.com
Address: No. 5, Wilson St., New York, U. S.
You can use the pattern modifier "e" in the regular expression preg_replace ". The function is to use the matching result as an expression and perform a new operation. For example:

 
  1. <? Php
  2. $ Html_body =
  3. "<HTML>
  4. <Body>
  5. <H1> TEST </H1>
  6. My Picture
  7. </Body>
  8. </HTML> ";
  9. // The HTML tags in the output result are all lowercase letters.
  10. Echo preg_replace (
  11. "/(</?) (W +) ([^>] *>)/e ",
  12. "'\ 1'. strtolower (' \ 2'). '\ 3'", // The mode variable here
    \ 2 converts strtolower to lowercase characters
  13. $ Html_body );
  14. ?>

The above is the detailed usage of the PHP function preg_replace (), and I hope to help you.


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.