preg_replace_callback()
Pass a callback function to preg_replace_callback() to compute the replacement dynamically based on each match.
Pass a callback function to preg_replace_callback() to compute the replacement dynamically based on each match.
<?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"
preg_replace_callback() accepts any callable — use an arrow function for concise single-expression replacements.