Converting preg_replace to preg_replace_callback for finding and replacing words with variables

一笑奈何 提交于 2020-04-07 09:15:31

问题


I have the following line of code:

$message = preg_replace('/\{\{([a-zA-Z_-]+)\}\}/e', "$$1", $body);

This replaces words surrounded by two curly brackets with variables of the same name. ie {{username}} gets replaced by $username.

I am trying to convert it to use preg_replace_callback. This is my code so far based on Googling, but I'm not really sure what I am doing! The error_log output is showing the variable name including the curly brackets.

$message = preg_replace_callback(
    "/\{\{([a-zA-Z_-]+)\}\}/",
        function($match){
            error_log($match[0]);
            return $$match[0];
        },
        $body
);

Any help greatly appreciated.


回答1:


Functions have their own variable scope in PHP, so anything you're trying to replace isn't available inside the function unless you make it explicitly so. I'd recommend putting your replacements in an array instead of individual variables. This has two advantages -- first, it allows you to easily get them inside the function scope and second, it provides a built-in whitelisting mechanism so that your templates can't accidentally (or intentionally) refer to variables that shouldn't be exposed.

// Don't do this:
$foo = 'FOO';
$bar = 'BAR';

// Instead do this:
$replacements = [
    'foo' => 'FOO',
    'bar' => 'BAR',
];

// Now, only things inside the $replacements array can be replaced.

$template = 'this {{foo}} is a {{bar}} and here is {{baz}}';
$message = preg_replace_callback(
    '/\{\{([a-zA-Z_-]+)\}\}/',
    function($match) use ($replacements) {
        return $replacements[$match[1]] ?? '__ERROR__';
    },
    $template
);

echo "$message\n";

This yields:

this FOO is a BAR and here is __ERROR__


来源:https://stackoverflow.com/questions/53873707/converting-preg-replace-to-preg-replace-callback-for-finding-and-replacing-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!