preg_replace_callback_array() function in PHP 7

PHPz
Release: 2023-08-19 13:42:01
forward
1593 people have browsed it

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)
Copy after login

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>
Copy after login

Output

The output of the above program code is −

7 number of "a" found
4 number of "b" found
5 number of "c" found
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template