如何用数组中的值替换多个#


How to replace multiple # with values from an array?

我不太确定这叫什么,但在编程中很常见,经常使用?而不是我在这个例子中使用的%。

假设我有一个字符串:

说:"用铝罐制造1%需要多少%?"

我想将%符号替换为数组中基于其索引和字符串中位置的特定值。在这种情况下:

['robots', 'laser gun']

结果是:

用铝罐制造激光枪需要多少个机器人

有没有什么方法可以在PHP中轻松地实现这一点?

只是添加到选项中:-)

<?php
$s=    "How many  %1'$s does it take the build a  %2'$s out of aluminum cans?";
$a=array('robots', 'laser gun');
echo vsprintf($s,$a)
?>

也许

sprintf ( "How many %s does it take the build a %s out of aluminum cans?", "robots", "laser gun" )

sprintf

下面的代码完成了这项工作:

$string = 'How many % does it take the build a % out of aluminum cans?';
$placeholders = ['robots', 'laser gun'];
echo call_user_func_array('sprintf', array_merge([str_replace('%', '%s', $string)], $placeholders));

我写了这个并测试了它,有效!

$randomstring = "How many % does it take the build a % out of aluminum cans?";
$array = array("robots", "laser gun");
for($x = 0;$x != count($array);$x++){
   $randomstring = preg_replace('/%/', $array[$x], $randomstring, 1);
}
echo $randomstring;

如果标记标记,则可以使用strtr来搜索和替换值。使用命名标记使代码更易于阅读。

$str = "How many {thing} does it take the build a {weapon} out of aluminum cans?";
echo strtr($str, [
    '{thing}'  => 'robots',
    '{weapon}' => 'laser gun',
]);