Summary of the use of PHP regular replacement functions preg_replace and preg_replace_callback

  • 2021-07-18 07:39:12
  • OfStack

When writing PHP template engine tool class, one regular replacement function commonly used before is preg_replace (), and with regular modifier/e, it can execute powerful callback function and realize template engine compilation (in fact, string replacement).

Reference blog post: The PHP function preg_replace () regularly replaces all qualified strings

Examples of applications are 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); // De-reversal meaning   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 is:


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

A closer look shows that the double quotes in $user ["password"] have been escaped, which is not what we want.

In order to output normally, we must reverse the meaning by 1. However, if the string itself contains inverted double quotation marks, we reverse the meaning at this time, and the original inverted meaning becomes non-inverted meaning. This result is not what we want, so this function is not good in this respect!

Later, a more professional regular replacement callback function preg_replace_callback () was found.


mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )
The behavior of this function is almost the same as that of the preg_replace() 1 Sample, except that it is not provided 1 A replacement Parameter, but specifies the 1 A callback Function. The function takes the matching array in the target string as an input parameter and returns a string for replacement.

Callback function callback:

1 callback function, which is called every time it needs to be replaced. When calling, the parameters obtained by the function are the results matched from subject. The callback function returns the string that really participates in the replacement. This is the signature of the callback function:


string handler ( array $matches )

As seen above, callback functions usually have only 1 parameter and are of array type.

List one example of the preg_replace_callback () function:

Example # 1 preg_replace_callback () and anonymous functions


<?php
/* 1 A unix A command-line filter of style is used to convert uppercase letters at the beginning 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 PHP 5.3, it is supported to pass multiple parameters to the anonymous function through the keyword use, 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 1 general function


<?php
// Increase the year in the text 1 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 a complete match
  // $matches[1] Is the first 1 Matching of capture subgroups
  // 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 do I call a non-static function inside a class? You can do the following:
For PHP 5.2, the second parameter looks like this array ($this, 'replace'):


<?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 PHP 5.3, the second parameter looks like "self:: replace":
Note that it can also be array ($this, 'replace').


<?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]);    
    }
  } 
}
?>


According to the knowledge points learned above, transform the template engine class 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 is:


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

It is exactly what we want, and the double quotation marks are not reversed!

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

JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript

Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg


Related articles: