Search code examples
phppreg-replacetemplate-engine

PHP preg_replace string within variables


I am using PHP 7.2.4, I want to make a template engine project, I try to use preg_replace to change the variable in the string, the code is here:

<?php
$lang = array(
    'hello' => 'Hello {$username}',
    'error_info' => 'Error Information : {$message}',
    'admin_denied' => '{$current_user} are not Administrator',
);

$username = 'Guest';
$current_user = 'Empty';
$message = 'You are not member !';

$new_string = preg_replace_callback('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', 'test', $string);

function test($matches)
{
    return '<?php echo '.$matches[1].'; ?>';
}

echo $new_string;

But it just show me

Hello , how are you?

It automatically remove the variable...

Update: here is var_dump:

D:\Wamp\www\t.php:5:string 'Hello <?php echo $username; ?>, how are you?' (length=44)

Solution

  • You may use create an associative array with keys (your variables) and values (their values), and then capture the variable part after $ and use it to check in the preg_replace_callback callback function if there is a key named as the found capture. If yes, replace with the corresponding value, else, replace with the match to put it back where it was found.

    Here is an example code in PHP:

    $values = array('username'=>'AAAAAA', 'lastname'=>'Smith');
    $string = 'Hello {$username}, how are you?';
    $new_string = preg_replace_callback('/\{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}/', function($m) use ($values) {
            return 'Hello <?php echo ' . (!empty($values[$m[1]]) ? $values[$m[1]] : $m[0]) . '; ?>';
        }, $string);
    
    var_dump($new_string);
    

    Output:

    string(47) "Hello Hello <?php echo AAAAAA; ?>, how are you?"
    

    Note the pattern charnge, I moved the parentheses after $:

    \{\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}
        ^                                        ^
    

    Actually, you may even shorten it to

    \{\$([a-zA-Z_\x7f-\xff][\w\x7f-\xff]*)}
                            ^^