Home  >  Article  >  Backend Development  >  preg_replace_callback_array() function in PHP 7

preg_replace_callback_array() function in PHP 7

PHPz
PHPzforward
2023-08-19 13:41:021589browse

PHP 7中的preg_replace_callback_array()函数

The Preg_replace_callback_array() function represents a regular expression in PHP 7 and replaces the use of callback functions. This function returns a string or array of strings to match a set of regular expressions and replace them using a callback function.

Syntax

preg_replace_callback_array(patterns, input, limit, count)

Parameter value:

  • pattern −It requires an associative array to associate the regular expression pattern with the callback function .
  • input/subject −It requires an array of strings to perform replacement.
  • limit −It is optional. By default -1 is used, meaning no limit. It sets a limit on how many substitutions can be made in each string.
  • count −It is also optional, just like limit. This variable will contain a number indicating how many substitutions were made after the function was executed.
  • flags −It can be a combination of preg_offset_capture and preg_unmatched_as_null flags, which affect the format of the matched array.
  • Return value −preg_replace_callback_array() returns a string or string array. If an error is found, a null value is returned. If a match is found, the new subject is returned, otherwise the unchanged subject is returned.

Preg_replace_callback_array(): Example

Demonstration

<html>
<head>
<title> PHP 7 Featuretutorialpoint:</title>
</head>
<body>
<?php
   $subject = &#39;AaaaaaaBbbbCccc&#39;;
   preg_replace_callback_array (
      [
         &#39;~[a]+~i&#39; => function ($match) {
            echo strlen($match[0]), &#39; number of "a" found&#39;, PHP_EOL;
         },
         &#39;~[b]+~i&#39; => function ($match) {
            echo strlen($match[0]), &#39; number of "b" found&#39;, PHP_EOL;
         },
         &#39;~[c]+~i&#39; => function ($match) {
            echo strlen($match[0]), &#39; number of "c" found&#39;, PHP_EOL;
         }
      ],
      $subject
   );
?>
</body>
</html>

Output

The output of the above program code is −

7 number of "a" found
4 number of "b" found
5 number of "c" found

The above is the detailed content of preg_replace_callback_array() function in PHP 7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete