PHP preg_replace_callback() Function

What is preg_replace_callback function?

If you want to search a string using a regular expression pattern and replace the match(s) with a custom function, use preg_replace_callback() function. With this function, not only one string but you can search an array of strings. Similarly, the searching regular expression pattern could be a string or an array. The function searches a string (the “subject” parameter) following a regular expression pattern (the “pattern” parameter) and replace the match(s) with a custom function or method (the “callback” parameter).

The preg_replace_callback() function is identical to preg_replace() function except it uses a callback function to generate a replacement string whereas preg_replace() function uses a regular expression to generate a replacement string.

Syntax:

preg_replace_callback(pattern, callback, subject, limit, count, flag)

Parameters:

pattern (Mandatory): It can either be a string (Check Example 1) or an array of strings (Check Example 2). This parameter is a regular expression that you’ll search to find matches.

callback (Mandatory): It is a callback function. For every match found in the “subject” parameter according to the “pattern” parameter, the preg_replace_callback() function calls this callback function and passes array of matched elements. Note, here, the first element is always the entire matched string, second element is the first matched sub-pattern, third element is the third matched sub-pattern and so on.

subject (Mandatory): This can either be a string or an array. This is the main string where the function searches.

  • If it is an array, the search and replacement are performed on every element of the array and the return value is also an array (Check example 3).
  • If it is an associative array, the keys are preserved in the returned value (Check example 4).

limit (Optional): It is a number that tells the maximum replacement number for each “pattern” in each “subject” string. Default number is -1 (which means no limit) (Check example 5).

count (Optional): If you specify this parameter as a variable, the variable stores number of replacement done by the function (Check example 6).

flags (Optional): You can use two values (PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL) combine or separately as flags to influence the format of the matches array.

Return Values:

  • It returns the “subject” parameter whether it is modified or not (Check any example).
  • It returns an array if the “subject” parameter is an array (Check example 3), otherwise it returns a string (Check example 1).
  • It returns NULL if an error occurred.

Examples:

Example 1:

<?php // EXAMPLE 1
$pattern = '/(\d{4})-(\d{2})-(\d{2})/';
$subject  = '2023-10-09';
function callback ($matches) {
    return $matches[2].'-'.$matches[3].'-'.$matches[1];
}
$return_value = preg_replace_callback($pattern, 'callback', $subject);
echo $return_value;
?>

Output:

10-09-2023

Example 2:

<?php
$patterns = array('/(\d{4})-(\d{2})-(\d{2})/');
$subject  = 'Today: 2023-10-09';
function callback1 ($matches) {
    return $matches[2].'/'.$matches[3].'/'.$matches[1];
}
$return_value = preg_replace_callback($patterns, 'callback1', $subject);
echo $return_value;
?>

Output:

Today: 10/09/2023

Example 3:

<?php
$string = array('World Bicycle Day is on 3rd June(03-06)', 'Software Freedom Day is on 15th September(15-09)');
$patterns = array('/(\d{2})-(\d{2})/');
function callback2($matches) {
    return $matches[2].'/'.$matches[1];
}
$retnrn_str = preg_replace_callback($patterns, 'callback2', $string);
for($i=0; $i<count($retnrn_str); $i++){
    echo $retnrn_str[$i]. "<br />";
}
?>

Output:

World Bicycle Day is on 3rd June(06/03)
Software Freedom Day is on 15th September(09/15)

Example 4:

<?php
$string = array("One" => "World Bicycle Day is on 3rd June(03-06)", "Two" => "Software Freedom Day is on 15th September(15-09)");
$patterns = array('/(\d{2})-(\d{2})/');
function callback3($matches) {
    return "<strong>". $matches[2].'/'.$matches[1]. "</strong>";
}
$retnrn_str = preg_replace_callback($patterns, 'callback3', $string);
echo $retnrn_str["One"]. "<br />";
echo $retnrn_str["Two"]. "<br />";
?>

Output:

World Bicycle Day is on 3rd June(06/03)
Software Freedom Day is on 15th September(09/15)

Example 5:

<?php
$pattern = '/(\d{2})-(\d{2})/';
$subject  = 'World Bicycle Day is on 3rd June(03-06). Software Freedom Day is on 15th September(15-09)';
function callback4 ($matches) {
    return "<strong>". $matches[2].'/'.$matches[1]. "</strong>";
}
$return_value = preg_replace_callback($pattern, 'callback4', $subject, 1);
echo $return_value;
?>

Output:

World Bicycle Day is on 3rd June(06/03). Software Freedom Day is on 15th September(15-09)

Example 6:

<?php
$pattern = '/(\d{2})-(\d{2})/';
$subject  = 'World Bicycle Day is on 3rd June(03-06). Software Freedom Day is on 15th September(15-09)';
function callback5 ($matches) {
    return "<strong>". $matches[2].'/'.$matches[1]. "</strong>";
}
$return_value = preg_replace_callback($pattern, 'callback5', $subject, -1, $count);
echo $count;
?>

Output:

2

PHP Version Support:

PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8

Summary: PHP preg_replace_callback() Function

preg_replace_callback() function searches a string using a regular expression pattern and replaces the match(s) with a custom function. It is a built-in pcre function in PHP.

Reference:

https://www.php.net/manual/en/function.preg-replace-callback.php