Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP – mb_ereg_replac_callback() function
In PHP, mb_ereg_replace_callback() function is used to perform a regular expression search and replace with multibyte support using a callback. It scans strings, matches them with a pattern, then replaces the matched text with the output of the callback function. This function is similar to mb_ereg_replace() but allows custom replacement logic through callbacks. It is supported in PHP 5.4 or higher versions.
Syntax
string mb_ereg_replace_callback(str $pattern, callback $callback, str $string, str $options)
Parameters
The function accepts the following four parameters −
$pattern − The regular expression pattern. May use multibyte characters.
$callback − A callback function that receives an array of matched elements and returns the replacement string.
$string − The input string to search and replace.
$options − Optional search options (default is null).
Return Value
Returns the modified string on success, FALSE on error, or NULL if the string is invalid for the current encoding.
Example 1: Using Named Function
This example demonstrates incrementing years in date strings using a named callback function −
<?php
$result = "April Fools day is 04/01/2019<br>";
$result.= "Next match is 12/24/2021<br>";
// 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
);
?>
April Fools day is 04/01/2020 Next match is 12/24/2022
Example 2: Using Anonymous Function
This example shows the same functionality using an anonymous function −
<?php
// anonymous function is used
$result = "April Fools day is 04/01/2019<br>";
$result.= "Next match is 12/24/2021<br>";
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
function ($matches) {
return $matches[1].($matches[2]+1);
},
$result
);
?>
April Fools day is 04/01/2020 Next match is 12/24/2022
Key Points
Anonymous functions are often preferred for simple callbacks to keep code concise
The callback receives an array where
$matches[0]is the full match and$matches[1],$matches[2], etc. are captured groupsSupports multibyte character encoding unlike standard regex functions
Conclusion
The mb_ereg_replace_callback() function provides powerful pattern replacement with custom logic through callbacks. Use anonymous functions for simple operations and named functions for complex or reusable logic.
