用 PHP 中的字符串数组替换多个通配符实例

Replace several instances of wildcard with an array of strings in PHP

我有一个字符串,其中包含单个通配符的多个实例:

An $X a $X keeps the $X away.

和一个包含替换项的数组:

["apple","day","doctor"]

我想用第一个数组值替换第一个通配符,用第二个数组值替换第二个通配符等,给出:

An apple a day keeps the doctor away.

很抱歉,如果在其他地方有人问过这个问题,但我找不到任何带有 单一 搜索和 多重 的示例替换,只有多次搜索多个替换,但通配符没有编号,所以这不合适。

谢谢。

(s)printf 应该按照您的要求进行。

我能想到的两个选项sprintf()list():

$sentence = "An %s a %s keeps the %s away.";
$array = ["apple","day","doctor"];
echo sprintf($sentence , $array[0], $array[1], $array[2]);

// or not a single wildcard.
$array = ["apple","day","doctor"];
list($apple, $day, $doctor) = $array ;
echo "An $apple a $day keeps the $doctor away.";