What are common issues when using PHP functions to replace tags in templates?

One common issue when using PHP functions to replace tags in templates is that the replacement may not work as expected if the tags are nested within each other. To solve this, you can use a recursive function to replace the innermost tags first before moving outwards.

function replaceTags($template, $tags) {
    foreach($tags as $tag => $value) {
        $template = str_replace("{{$tag}}", $value, $template);
    }
    
    return $template;
}

function replaceNestedTags($template, $tags) {
    $replacedTemplate = $template;
    
    do {
        $template = $replacedTemplate;
        $replacedTemplate = replaceTags($template, $tags);
    } while ($replacedTemplate !== $template);
    
    return $replacedTemplate;
}

$template = "<h1>Hello, {name}!</h1>";
$tags = array('name' => 'John');

$finalTemplate = replaceNestedTags($template, $tags);
echo $finalTemplate;