Backend Development 4 min read

Using preg_replace_callback in PHP for Regex Replacement with Callbacks

The article explains PHP’s preg_replace_callback function, detailing its parameters and behavior, and provides three practical examples that demonstrate using anonymous and named callbacks to transform input strings, increment dates, and recursively parse custom tags into nested HTML elements.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using preg_replace_callback in PHP for Regex Replacement with Callbacks

preg_replace_callback() performs a regular‑expression search and replaces matches using a user‑defined callback function, behaving like preg_replace() except that the replacement is generated by the callback.

Parameters: pattern (string or array to search), callback (callable that receives matches and returns the replacement string), subject (string or array to be processed), limit (maximum number of replacements per pattern, default -1 for unlimited), and count (optional variable that receives the number of replacements performed).

Example 1 reads lines from STDIN and converts the first character of each line to lowercase using an anonymous function as the callback.

\s*\w|', function($matches) {
        return strtolower($matches[0]);
    }, $line);
    echo $line;
}
fclose($fp);
?>

Example 2 shows how to increment the year part of dates in a text by one using a named callback function next_year that adds one to the captured year group.

Example 3 demonstrates a recursive parsing of custom [indent]…[/indent] tags, converting them into nested <div> elements with increased left margin, using preg_replace_callback() together with a recursive function.

' . $input[1] . '
';
    }
    return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}
$output = parseTagsRecursive($input);
echo $output;
?>
backendregexcallbackpreg_replace_callback
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.