SyntaxStudy
Sign Up
PHP preg_replace_callback() for Dynamic Replacements
PHP Intermediate 5 min read

preg_replace_callback() for Dynamic Replacements

preg_replace_callback()

Pass a callback function to preg_replace_callback() to compute the replacement dynamically based on each match.

Example
<?php
// Convert Markdown headers to HTML
$html = preg_replace_callback(
    "/^(#{1,6})\s+(.+)$/m",
    function (array $matches): string {
        $level = strlen($matches[1]);
        return "<h{$level}>{$matches[2]}</h{$level}>";
    },
    $markdown
);

// Currency formatting
$result = preg_replace_callback(
    "/\$(\d+)/",
    fn($m) => "$" . number_format((int) $m[1], 2),
    "$1000 and $250 spent"
);
// "$1,000.00 and $250.00 spent"
Pro Tip

preg_replace_callback() accepts any callable — use an arrow function for concise single-expression replacements.