Search code examples
phpregexreplaceassociative-arrayplaceholder

Replace double curly brace wrapped placeholders with the corresponding array value


I am trying to replace dynamic placeholders with the appropriate value in an associative array.

$string = '{{name}} is {{age}} years old';

$array = array(
    'name' => 'John Doe',
    'age' => '27'
);

The pattern I have so far is \{{([a-zA-Z0-9]+)\}} however this only seems to match one pair of braces.

I'm also having a problem looping through results in preg_match_all().


Solution

  • preg_replace_callback seems like a good candidate.

    $str = "{{name}} is {{age}} years old";
    $values = array( 'name' => 'John Doe', 'age' => '27' );
    echo preg_replace_callback("/\{{([a-z0-9]+?)\}}/i", function ($result)
    use ($values) {
       if (isset($result[1])) {
          return $values[$result[1]];
       }
    }, $str);
    

    The main issue is that {{[a-z]+}} will match from {{name ... age}}. Using the ? makes the + reluctant so it only matches up to the first } rather than the last.