开发者

PHP Regex expression needed

Ok, I have this regex here:

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

$params = an array where the key = 'scripturl' and the value = 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 reg ex 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 开发者_StackOverflow中文版a separate regex just for this that is fine also.

Thanks :)


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);


something like this should be able to it. it will catch everything between brackets

EDIT:

function replaceTemplateVariable($match){
  global $$match[1];
  return $$match[1];
}
preg_replace_callback('/\{[^\}]+\}/', 'replaceTemplateVariable', $text);

Also preg_replace_callback could help to make your code simpler

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜