用不同的值替换多次出现的字符串 [英] Replace multiple occurrences of a string with different values
问题描述
我有一个脚本可以生成包含某些标记的内容,我需要用单独循环产生的不同内容替换每次出现的标记.
I have a script that generates content containing certain tokens, and I need to replace each occurrence of a token, with different content resulting from a separate loop.
使用 str_replace 将所有出现的标记替换为 相同 内容很简单,但我需要用循环的下一个结果替换每次出现.
It's simple to use str_replace to replace all occurrences of the token with the same content, but I need to replace each occurrence with the next result of the loop.
我确实看到了这个答案:搜索并在 PHP5 中用多个/不同的值替换多个值?
I did see this answer: Search and replace multiple values with multiple/different values in PHP5?
但是它可以从我没有的预定义数组中工作.
however it is working from pre-defined arrays, which I don't have.
示例内容:
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.
为了论证,我需要用这个简单循环生成的内容替换每次出现的 %%token%% :
I need to replace each occurrence of %%token%% with content generated, for argument's sake, by this simple loop:
for($i=0;$i<3;$i++){
$token = rand(100,10000);
}
因此将每个 %%token%% 替换为不同的随机数值 $token.
So replace each %%token%% with a different random number value $token.
这是我没有看到的简单事情吗?
Is this something simple that I'm just not seeing?
谢谢!
推荐答案
我认为您无法使用任何搜索和替换功能来执行此操作,因此您必须自己编写替换代码.
I don't think you can do this using any of the search and replace functions, so you'll have to code up the replace yourself.
在我看来,这个问题与 explode()
配合得很好.因此,使用您提供的示例令牌生成器,解决方案如下所示:
It looks to me like this problem works well with explode()
. So, using the example token generator you provided, the solution looks like this:
$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);
}
这篇关于用不同的值替换多次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!