PHP Regular Replacement function preg_replace and Preg_replace_callback use summary _php tips

Source: Internet
Author: User

When writing the PHP template Engine tool class, a previously used regular substitution function of preg_replace (), plus the regular modifier/e, can perform powerful callback functions that implement template engine compilation (in fact, string substitution).

For more information, reference Blog: php function preg_replace () Replace all strings that match the criteria

Examples of applications are as follows:

Copy Code code as follows:

<?php
/**
* Template Resolution Class
*/
Class Template {

Public function compile ($template) {

If logic
$template = Preg_replace ("/\<\!\-\-\{if\s+" (. +?) \}\-\-\>/e "," \ $this->iftag (' \\1 '), $template);

return $template;
}

/**
* If label
*/
protected function Iftag ($STR) {

$str = Stripslashes ($STR); To reverse righteousness.

Return ' <?php if ('. $str. ') {?> ';
}
}

$template = ' xxx<!--{if $user [\ ' username\ ']}-->yyy<!--{if $user [' Password ']}-->zzz '];

$tplComplier = new Template ();

$template = $tplComplier->compile ($template);

Echo $template;

?>

The output results are:

Copy Code code as follows:

xxx<?php if ($user [' userName ']) {>yyy<?php if ($user [\ password\ "]) {? >zzz

After careful observation, we find that the double quotes in the $user ["password"] are escaped, which is not the result we want.

In order to be able to output normally, you must also reverse righteousness, but if the string itself contains inverted double quotes, we are at this time inversion of righteousness, the original reversal of righteousness has become a reversal of righteousness, this result is not what we want, so that this function in this respect with the bad!

Later, a more professional-level replacement callback function, Preg_replace_callback (), was found.

Copy Code code as follows:

Mixed Preg_replace_callback (mixed pattern, callback callback, mixed subject [, int limit])
The behavior of this function is almost the same as Preg_replace (), except that instead of providing a replacement parameter, you specify a callback function. The function takes an array of matches in the target string as an input parameter and returns a string for substitution.

callback function callback:

A callback function that is invoked each time a replacement is required, and the arguments that are obtained by the call-time function are the result of matching from the subject. The callback function returns the string that really participates in the substitution. This is the signature of the callback function:

Copy Code code as follows:

String handler (array $matches)

As you can see above, the callback function usually has only one argument and is an array type.

List some examples of preg_replace_callback () functions:

Example #1 Preg_replace_callback () and anonymous functions

Copy Code code as follows:

<?php
/* A UNIX-style command-line filter that converts uppercase letters in the beginning portion of a paragraph to lowercase. */
$fp = fopen ("Php://stdin", "R") or Die ("can" t read stdin);
while (!feof ($fp)) {
$line = fgets ($FP);
$line = Preg_replace_callback (
' |<p>\s*\w| ',
function ($matches) {
return Strtolower ($matches [0]);
},
$line
);
Echo $line;
}
Fclose ($FP);
?>

If the callback function is an anonymous function, in PHP5.3, the use of the keyword allows multiple parameters to be passed to the anonymous function, as follows:

Copy Code code 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

Copy Code code as follows:

<?php
Increases the year in the text by one year.
$text = "April fools day is 04/01/2002\n";
$text. = "Last Christmas was 12/24/2001\n";
callback function
function Next_year ($matches) {
Usually: $matches [0] is the completed match
$matches [1] is the first match to capture subgroups
Analogy
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 method

How do I call a non-static function inside a class? You can do this by doing the following:
For PHP 5.2, the second argument looks like this array ($this, ' replace '):

Copy Code code 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 argument is like this "self::replace":
Note that it can also be an array ($this, ' replace ').

Copy Code code 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:

Copy Code code as follows:

<?php
/**
* Template Resolution Class
*/
Class Template {

Public function compile ($template) {

If logic
$template = Preg_replace_callback ("/\<\!\-\-\{if\s+" (. +?) \}\-\-\>/", Array ($this, ' Iftag '), $template);

return $template;
}

/**
* If label
*/
protected function Iftag ($matches) {
Return ' <?php if ('. $matches [1]. ') {?> ';
}
}

$template = ' xxx<!--{if $user [\ ' username\ ']}-->yyy<!--{if $user [' Password ']}-->zzz '];

$tplComplier = new Template ();

$template = $tplComplier->compile ($template);

Echo $template;

?>

The output results are:

Copy Code code as follows:

xxx<?php if ($user [' userName ']) {>yyy<?php if ($user ["password"]) {? >zzz

It is the result we want, and the double quotes are not reversed!

PS: About regular, this site also provides 2 very simple and practical regular expression tools for everyone to use:

JavaScript Regular expression online test tool:
Http://tools.jb51.net/regex/javascript

Regular expression online generation tool:
Http://tools.jb51.net/regex/create_reg

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.