carry0987
carry0987

Reputation: 127

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)

Upvotes: 1

Views: 940

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

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]*)}
                        ^^

Upvotes: 1

Dave
Dave

Reputation: 5191

I'm a fan of keeping it simple so I would use str_replace since it will also change all instances which may come in handy as you go forward.

$string = 'Hello {$username}, how are you?';
$username = 'AAAAAA';
echo str_replace('{$username}',$username,$string);

Upvotes: 0

ADarkHero
ADarkHero

Reputation: 50

Do you want something like this?

<?php
    $string = 'Hello {$username}, how are you?';
    $username = 'AAAAAA';
    $new_string = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/', $username, $string);
    echo $new_string;

The result is:

Hello AAAAAA, how are you?

The more simple way would be to just write

<?php
$username = 'AAAAAA';
$string = 'Hello '.$username.', how are you?';

Upvotes: 0

Related Questions