Search code examples
phpregexpreg-replaceplaceholdercurly-braces

Replace curly braced placeholders where the placeholder name starts with a dollar sign


Ok, I have this regex here:

$text = preg_replace('/\{\$(\w+)\}/e', '$params["$1"]', $text);

$params is an array where the key is scripturl and the value is what to replace it with.

So an example text would be {$scripturl} and passing through to this would give me ' . $scripturl . ' when I pass to $params an array that looks like so:

array('scripturl' => '\' . $scripturl . \'');

But I also need it to support brackets within the curly braces {}.

So I need this: {$context[forum_name]} to be caught with this regex as well.

So something like this should work:

array('context[forum_name]' => '\' . $context[\'forum_name\'] . \'');

So it would need to return ' . $context['forum_name'] . '

How can I make this possible within the preg_replace() that I am using?

If I need to create a separate regex just for this that is fine also.


Solution

  • You may need to use preg_replace_callback() for that, but if you can get it working with the /e eval-modifier, then great.

    Try changing the regexp to the following:

    $text = preg_replace('/\{\$([\w\"\[\]]+)\}/e', '$params["$1"]', $text);