Advanced preg_replace
Combine regex with callbacks for powerful text transformation: sanitization, Markdown-to-HTML, template variable replacement.
Combine regex with callbacks for powerful text transformation: sanitization, Markdown-to-HTML, template variable replacement.
<?php
// Template variable substitution
function renderTemplate(string $template, array $vars): string {
return preg_replace_callback(
"/\{\{\s*(\w+)\s*\}\}/",
function (array $match) use ($vars): string {
return htmlspecialchars($vars[$match[1]] ?? "", ENT_QUOTES, "UTF-8");
},
$template
);
}
echo renderTemplate("Hello, {{ name }}! You have {{ count }} messages.", [
"name" => "Alice",
"count" => "3",
]);
// "Hello, Alice! You have 3 messages."
Always escape output in callbacks with htmlspecialchars() when rendering user data into HTML templates.