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

I want to replace not only simple variables but also an array . There is an answer Alex Howansky the replacement for the 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 works fine for {TEST} a {THING}.

For a variable call variable for an array, I need ${$array}['key']

( StackOverflow Question/2424399 / ... ). So I tried to do a second pass:

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

      

But in the output I get a string $\{$array\}["key"]

instead of the value of $ array ["key"].

How do I replace substrings in a template with array variables?

+3


source to share


1 answer


I couldn't get it to parse properly with preg_replace

, so I used a callback:

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

$array['key'] = 'something';

$result = preg_replace_callback('/\{([a-z]+)\["([a-z]+)"\]\}/',
                                function($m) use($array){
                                    return ${$m[1]}[$m[2]];
                                },
                                $str);

      



If you don't know the name of the array to be passed to the function, you need to make sure it is defined in the global scope and then access it like this:

$result = preg_replace_callback('/\{([a-z]+)\["([a-z]+)"\]\}/',
                                function($m) {
                                    ${$m[1]} = $GLOBALS[$m[1]];
                                    return ${$m[1]}[$m[2]];
                                },
                                $str);

      

+1


source







All Articles