This article mainly introduces the use summary of PHP regular expression replacement functions preg_replace and preg_replace_callback. This article is summarized when writing a template engine to meet a special requirement, if you need a regular expression, refer to the common regular expression replacement function preg_replace () when compiling the PHP template engine tool class, and add the regular expression modifier/e, you can execute powerful callback functions to compile the template engine (which is actually a string replacement ).
For details, refer to the blog post: Use the PHP function preg_replace () to replace all qualified strings with regular expressions.
The application example is as follows:
The code is as follows:
<? Php
/**
* Template parsing class
*/
Class Template {
Public function compile ($ template ){
// If logic
$ Template = preg_replace ("/\ <\! \-\ {If \ s + (. + ?) \} \-\>/E "," \ $ this-> ifTag ('\ 1') ", $ template );
Return $ template;
}
/**
* If tag
*/
Protected function ifTag ($ str ){
// $ Str = stripslashes ($ str); // reverse the meaning
Return '<? Php if ('. $ str.') {?> ';
}
}
$ Template = 'XXX Yyy Zzz ';
$ TplComplier = new Template ();
$ Template = $ tplComplier-> compile ($ template );
Echo $ template;
?>
Output result:
The code is as follows:
Xxx <? Php if ($ user ['username']) {?> Yyy <? Php if ($ user [\ "password \"]) {?> Zzz
Observe carefully and find that the double quotation marks in $ user ["password"] are escaped. this is not the expected result.
To ensure normal output, you must also reverse the meaning. However, if the string itself contains inverted double quotation marks, we will reverse the meaning at this time, and the original reverse meaning will become non-inverted, this result is not what we want, so this function is uncomfortable in this regard!
Later, we found a more professional callback function preg_replace_callback () for regular expression replacement ().
The code is as follows:
Mixed preg_replace_callback (mixed pattern, callback, mixed subject [, int limit])
The behavior of this function is almost the same as that of preg_replace (), except that a replacement parameter is provided, but a callback function is specified. This function uses the matching array in the target string as the input parameter and returns the string to be replaced.
Callback function callback:
A callback function is called every time it needs to be replaced. during the call, the parameters obtained by the function are the matching results from the subject. The callback function returns the string to be replaced. This is the signature of the callback function:
The code is as follows:
String handler (array $ matches)
As shown above, the callback function usually has only one parameter and is of the array type.
List some instances related to the preg_replace_callback () function:
Example #1 preg_replace_callback () and anonymous functions
The code is as follows:
<? Php
/* A unix-style command line filter that converts uppercase letters at the beginning of a paragraph to lowercase letters. */
$ Fp = fopen ("php: // stdin", "r") or die ("can't read stdin ");
While (! Feof ($ fp )){
$ Line = fgets ($ fp );
$ Line = preg_replace_callback (
'|
\ S * \ w | ',
Function ($ matches ){
Return strtolower ($ matches [0]);
},
$ Line
);
Echo $ line;
}
Fclose ($ fp );
?>
If the callback function is an anonymous function, multiple parameters can be passed to the anonymous function through the keyword use in PHP5.3, as shown below:
The code is as follows:
<? Php
$ String = "Some numbers: one: 1; two: 2; three: 3 end ";
$ Ten = 10;
$ Newstring = preg_replace_callback (
'/(\ D + )/',
Function ($ match) use ($ ten) {return ($ match [0] + $ ten ));},
$ String
);
Echo $ newstring;
# Prints "Some numbers: one: 11; two: 12; three: 13 end ";
?>
Example #2 preg_replace_callback () and general functions
The code is as follows:
<? Php
// Increase the year in the text by one year.
$ Text = "maid day is 04/01/2002 \ n ";
$ Text. = "Last christmas was 12/24/2001 \ n ";
// Callback function
Function next_year ($ matches ){
// Generally: $ matches [0] indicates a complete match.
// $ Matches [1] is the first matching capture sub-group
// And so on
Return $ matches [1]. ($ matches [2] + 1 );
}
Echo preg_replace_callback (
"| (\ D {2}/\ d {2}/) (\ d {4}) | ",
"Next_year ",
$ Text );
?>
Example #3 preg_replace_callback () and class methods
How can I call non-static functions within a class? You can perform the following operations:
For PHP 5.2, the second parameter is like this array ($ this, 'replace '):
The code is as follows:
<? Php
Class test_preg_callback {
Private function process ($ text ){
$ Reg = "// {([0-9a-zA-Z \-] +) \ :( [0-9a-zA-Z \-] + ):? \}/";
Return preg_replace_callback ($ reg, array ($ this, 'replace '), $ text );
}
Private function replace ($ matches ){
If (method_exists ($ this, $ matches [1]) {
Return @ $ this-> $ matches [1] ($ matches [2]);
}
}
}
?>
For PHP5.3, the second parameter is like this "self: replace ":
Note: It can also be array ($ this, 'replace ').
The code is as follows:
<? Php
Class test_preg_callback {
Private function process ($ text ){
$ Reg = "// {([0-9a-zA-Z \-] +) \ :( [0-9a-zA-Z \-] + ):? \}/";
Return preg_replace_callback ($ reg, "self: replace", $ text );
}
Private function replace ($ matches ){
If (method_exists ($ this, $ matches [1]) {
Return @ $ this-> $ matches [1] ($ matches [2]);
}
}
}
?>
Based on the knowledge learned above, the template engine class is transformed as follows:
The code is as follows:
<? Php
/**
* Template parsing class
*/
Class Template {
Public function compile ($ template ){
// If logic
$ Template = preg_replace_callback ("/\ <\! \-\ {If \ s + (. + ?) \} \-\>/", Array ($ this, 'iftag'), $ template );
Return $ template;
}
/**
* If tag
*/
Protected function ifTag ($ matches ){
Return '<? Php if ('. $ matches [1].') {?> ';
}
}
$ Template = 'XXX Yyy Zzz ';
$ TplComplier = new Template ();
$ Template = $ tplComplier-> compile ($ template );
Echo $ template;
?>
Output result:
The code is as follows:
Xxx <? Php if ($ user ['username']) {?> Yyy <? Php if ($ user ["password"]) {?> Zzz
It is exactly what we want. double quotation marks are not reversed!