Preg_replace_callback_array() in PHP 7

PHPServer Side ProgrammingProgramming

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

Syntax

preg_replace_callback_array(patterns, input, limit, count)

Parameter Values:

  • pattern − It requires an associate array to associate the regular expression patterns to callback functions.
  • input/subject −It requires an array of strings to perform replacements.
  • limit −It is optional. -1 is used for default, which means it is unlimited. It sets a limit to how many replacements can be done in each string.
  • count −It is also optional like the limit. This variable will contain a number, indicating how many replacements were performed after the function gets to execute.
  • flags −It can be a combination of the preg_offset_captureandpreg_unmatched_as_null flags, which impact the format of the matched array.
  • Return Values −preg_replace_callback_array() returns a string or an array of strings.If an error is found, then it will return a null value.If matches are found, the new subject will be returned, otherwise,the subject will be returned unchanged.

Preg_replace_callback_array() : Example

Live Demo

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

Output

The output for the above program code is −

7 number of "a" found
4 number of "b" found
5 number of "c" found
raja
Published on 13-Mar-2021 06:29:15
Advertisements