强制替换 PHP 字符串中的变量


Force variable replacement in PHP string

有没有办法强制字符串求值(就像双引号字符串/heredoc 一样)?

例如,是否有一些干净的方法来执行此操作:

<?php
$mystring = <<<'MS'
hello {$adjectives['first']} world
MS;
$adjectives = array('first'=>'beautiful');
// here I want to print 'hello beautiful world' 
// instead of 'hello {$adjectives['first']} world'
echo evaluate($mystring); // evaluate is not a real function
?>
您可以使用

eval,因为您计划仅在自己创建的字符串上使用它。如果字符串(或替换项)超出您的控制范围,则不要使用 eval

$mystring = <<<'MS'
hello %s world
MS;
$adjectives = array('first'=>'beautiful');
eval('$parsed = ' . json_encode($mystring) . ';');
echo($parsed);

见 http://sandbox.onlinephpfunctions.com/code/b1f6afc24efbc685f738dc1e7fd3668afdf5b7d0

正如NATH所建议的那样,sprintf将为您完成这项工作,而不会受到eval的安全影响

$mystring = <<<'MS'
hello %s world
MS;
$adjectives = array('first' => 'beautiful');
echo sprintf($mystring, $adjectives['first']);

我强烈建议避免使用eval()。我认为这是危险的,缓慢的,而且通常是一种不好的做法。相反,使用vsprintf()应该可以为您解决问题。

// Use argument swapping (%1'$s instead of %s) to explicitly specify which
// position in the array represents each value. Useful if you're swapping out
// multiple values.
$mystring = <<<MS
hello %1'$s world
MS;
$adjectives = array('first'=>'beautiful');
echo vsprintf($mystring, $adjectives);

是的,你几乎得到了它。

看看这个例子的 eval @ php.net

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "'n";
eval("'$str = '"$str'";");
echo $str. "'n";
?>

但请注意,使用 eval 是危险的,如果处理不当,可能会受到各种攻击。

也许更好的解决方案是使用某种占位符。

$str = "This is a __first__ world";
$adjectives = array('first'=>'beautiful');
foreach ($adjectives as $k=>$v) {
   $str = preg_replace('/__'.$k.'__/', $v, $str); 
}
echo $str;