PHP – mb_ereg_replac_callback() function


In PHP, mb_ereg_replace_callback() function is used to perform a regular expression search and replace it with a multibyte support using a callback. It will scan the strings and match them with a pattern, then it will replace the matched text with the output of the callback function. This function is like the mb_ereg_replace() function. It is supported in PHP 5.4 or higher version.

Syntax

string mb_ereg_replace_callback(str $pattern, callback $callback, str $string, str $options)

Parameters

The function accepts the following four parameters −

  • $pattern − This parameter is used for the regular expression pattern. It may use multibyte characters in a pattern.

  • $callback − This parameter will be called and passed an array of matched elements in the subject string and it should return the replacement string.

  • $string − This parameter is used to check the string.

  • $options − This parameter is used to check the search option.

Note − The callback function often needs for a mb_ereg_replace_callback() in just one place. You can also use an anonymous function to declare the callback within the call mb_ereg_replace_callback(). By using this, we can have all the information for the call in one place and do not mess the function namespace with a callback function's name which is not used anywhere else.

Return Values

mb_ereg_replace_callback() returns success for the resultant string or it returns False on error. It returns NULL if the string is not valid for the current encoding.

Example 1

<?php
   $result = "April Fools day is 04/01/2019
"; $result.= "Next match is 12/24/2021
"; // callback function function next_year($matches) { return $matches[1].($matches[2]+1); } echo mb_ereg_replace_callback( "(\d{2}/\d{2}/)(\d{4})", "next_year", $result); ?>

Output

April Fools day is 04/01/2020
Next match is 12/24/2022

Example 2

Using anonymous function

<?php
   // anonymous function is used
   $result = "April Fools day is 04/01/2019
";    $result.= "Next match is 12/24/2021
";    echo mb_ereg_replace_callback(       "(\d{2}/\d{2}/)(\d{4})",       function ($matches) {          return $matches[1].($matches[2]+1); }, $result); ?>

Output

April fools day is 04/01/2020
Next match is 12/24/2022

Note − In Example 2, anonymous functions are used and a callback function is removed, but the output still remains the same.

Updated on: 11-Oct-2021

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements