PHP Replace {var['key']} in string with array variable

Viewed 403

I want to replace not only simple variables but also array ones. There is an answer of Alex Howansky about replace for simple variables:

$str = 'this is {TEST} a {THING} to test and a {array["key"]} var';

$TEST = 'one';
$THING = 'two';

$result = preg_replace('/\{([A-Z]+)\}/e', "$$1", $str);

It's work fine for {TEST} an {THING}.

For call variable variable for array I need ${$array}['key'] (https://stackoverflow.com/a/20216265/1056384). So I have tried to do second pass:

$result = preg_replace('/\{([a-z]+)\["([a-z]+)"\]\}/', "$\{$$1\}["$2"]", $result);

But in the output I have get the string $\{$array\}["key"] instead of value of $array["key"].

How to replace substrings in template with array variables?

1 Answers
Related