PHP keep me from eval ;) Variables inside string

落花浮王杯 提交于 2019-12-08 14:22:32

I don't think there is a way to get that to work. You are trying something like this:

$var = "cute text";
echo 'this is $var';

The single quotes are preventing the interpreter from looking for variables in the string. And it is the same, when you echo a string variable.

The solution will be a simple str_replace.

echo str_replace('$title', $title, $string);

But in this case I really suggest Template variables that are unique in your text.

Your example is a bit abstract. But it seems like you could do pretty much what the template engines do for these case:

function test($string){
   $title = 'please print';

   $vars = get_defined_vars();
   $string = preg_replace('/[$](\w{3,20})/e', '$vars["$1"]', $string);

   echo $string;
}

Now actually, /e is pretty much the same as using eval. But at least this only replaces actual variable names. Could be made a bit more sophisticated still.

You just don't do that, a variable is a living thing, it's against its nature to store it like that, flat and dead in a string in the database.

If you want to replace some parts of a string with the content of a variable, use sprintf().

Example

$stringFromTheDb = '<div>%s is not %s</div>';

Then use it with:

$finalString = sprintf($stringFromTheDb, 'this', 'that');

echo $finalString;

will result in:

<div>this is not that</div>

If you know that the variable inside the div is $title, you can str_replace it.

function test($string){
  $title = 'please print';
  echo str_replace('$title', $title, $string);
}

If you don't know the variables in the string, you can use a regex to get them (I used the regex from the PHP manual).

function test($string){
  $title = 'please print';
  $vars = '/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
  preg_match_all($vars, $string, $replace);
  foreach($replace[0] as $r){
    $string = str_replace('$'.$r, $$r, $string);
  }
  echo $string;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!