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
- <? Php
- // String
- $ String = "Name: {Name} <br> nEmail:
{Email} <br> nAddress: {Address} <br> n ";
- // Mode
- $ Patterns = array (
- "/{Address }/",
- "/{Name }/",
- "/{Email }/"
- );
- // Replace the string
- $ Replacements = array (
- "No. 5, Wilson St., New York, U. S. ",
- "Thomas Ching ",
- "Tom@emailaddress.com ",
- );
- // Output mode replacement result
- Print preg_replace ($ patterns,
$ Replacements, $ string );
- ?>
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:
- <? Php
- $ Html_body =
- "<HTML>
- <Body>
- <H1> TEST </H1>
- My Picture
- </Body>
- </HTML> ";
- // The HTML tags in the output result are all lowercase letters.
- Echo preg_replace (
- "/(</?) (W +) ([^>] *>)/e ",
- "'\ 1'. strtolower (' \ 2'). '\ 3'", // The mode variable here
\ 2 converts strtolower to lowercase characters
- $ Html_body );
- ?>
The above is the detailed usage of the PHP function preg_replace (), and I hope to help you.