用不同的值替换多次出现的字符串

Jon*_*ute 3 php string replace str-replace

我有一个脚本生成包含某些令牌的内容,我需要替换每个出现的令牌,其中不同的内容来自单独的循环.

使用str_replace简单地用相同的内容替换所有出现的令牌很简单,但是我需要用循环的下一个结果替换每个出现.

我确实看到了这个答案:在PHP5中搜索并用多个/不同的值替换多个值?

但它是从预定义的数组工作,我没有.

示例内容:

This is an example of %%token%% that might contain multiple instances of a particular
%%token%%, that need to each be replaced with a different piece of %%token%% generated 
elsewhere.
Run Code Online (Sandbox Code Playgroud)

为了参数,我需要用生成的内容替换每次出现的%% token %%,这个简单的循环:

for($i=0;$i<3;$i++){
    $token = rand(100,10000);
}
Run Code Online (Sandbox Code Playgroud)

因此,使用不同的随机数值$ token替换每个%%标记%%.

这个简单的东西,我只是没有看到?

谢谢!

Rya*_*yne 5

我不认为你可以使用任何搜索和替换功能来执行此操作,因此您必须自己编写替换代码.

在我看来,这个问题很适合explode().因此,使用您提供的示例令牌生成器,解决方案如下所示:

$shrapnel = explode('%%token%%', $str);
$newStr = '';
for ($i = 0; $i < count($shrapnel); ++$i)  {
    // The last piece of the string has no token after it, so we special-case it
    if ($i == count($shrapnel) - 1)
        $newStr .= $shrapnel[$i];
    else
        $newStr .= $shrapnel[$i] . rand(100,10000);
}
Run Code Online (Sandbox Code Playgroud)