SyntaxStudy
Sign Up
PHP Advanced preg_replace Techniques
PHP Intermediate 5 min read

Advanced preg_replace Techniques

Advanced preg_replace

Combine regex with callbacks for powerful text transformation: sanitization, Markdown-to-HTML, template variable replacement.

Example
<?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."
Pro Tip

Always escape output in callbacks with htmlspecialchars() when rendering user data into HTML templates.