The mb_ereg_replace_callback() function is an inbuilt function in PHP that is used to replace a regular expression match in a string using the callback function.
Syntax:
mb_ereg_replace_callback( $pattern, $callback,$string,$options): string|false|null
Parameters: The function accepts four parameters that are described below.
- $pattern: A pattern is a regular expression pattern that is used for replacing a string. It must be a valid regular expression pattern.
- $callback: A callback function is to be called for each match. The function should accept one parameter (an array containing the match information) and return the replacement string.
- $string: The input string to search in.
- $options: This is an optional parameter. Possible values for this parameter are: ‘m’ for multiline, ‘s’ for single line, and ‘r’ using Unicode rules when matching.
Return values: This function is the input string with all matches of the pattern replaced by the result of the callback function, as a string when it is true, & when it is false then it will give an error. The null will be returned when the string is invalid for the current encoding.
Example 1: The following program demonstrates the mb_ereg_replace_callback() function.
PHP
<?php $string = "I love cats and dogs" ; $pattern = "[a-z]" ; $callback = function ( $match ) { return mb_strtoupper( $match [0]); }; $replaced_string = mb_ereg_replace_callback( $pattern , $callback , $string ); echo "The string '$string' with matches replaced is '$replaced_string'." ; ?> |
The string 'I love cats and dogs' with matches replaced is 'I LOVE CATS AND DOGS'.
Example 2: The following program demonstrates the mb_ereg_replace_callback() function.
PHP
<?php $string = "Hello world" ; $pattern = "[w]" ; $replaced_string = mb_ereg_replace_callback( $pattern , function ( $matches ) { $first_letter = $matches [0]; if (mb_strtolower( $first_letter ) == "w" ) { return mb_strtoupper( $first_letter ); } else { return $first_letter ; } }, $string ); echo "The string '$string' with matches replaced is ' $replaced_string '."; ?> |
Output:
The string 'Hello world' with matches replaced is 'Hello World'.
Reference: https://www.php.net/manual/en/function.mb-ereg-replace-callback.php