简体   繁体   中英

Replacing variable names in string with actual variables

I want to replace variable names in a string with the actual variables. The string would look like this:

Hello $person->fullname$ Your login-ID is $person->id and your password is $person->password

The code should then replace the stuff after $ with the actual variables, ie

$string = 'Hello'. $person->fullname .'\nYour login-ID is'. $person->id .'and your password is'. $person->password 

This would mean replacing a $person->id with

'. $person->id.'

I guess I should use preg_replace, but I have no idea how I can make sure to match anything between $ and the next space character. What do I have to use?

Try the below code:

$a = 'Hello $person->fullname Your login-ID is $person->id and your password is $person->password';
$words = explode(' ',$a);
$output = "";
foreach($words as $word){
    if($word[0] == '$'){
        $word = "'.".$word.".'";
    }
    $output = $output.$word." ";
}

The $output string will be "Hello '.$person->fullname.' Your login-ID is '.$person->id.' and your password is '.$person->password.' " "Hello '.$person->fullname.' Your login-ID is '.$person->id.' and your password is '.$person->password.' "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM