[英]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你好 $person->fullname$ 你的登录 ID 是 $person->id 你的密码是 $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 替换为
'. '. $person->id.' $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.我想我应该使用 preg_replace,但我不知道如何确保匹配 $ 和下一个空格字符之间的任何内容。 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.' "
$output 字符串将是"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.' "
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.