【发布时间】:2011-11-24 12:31:35
【问题描述】:
我有一个生成包含某些标记的内容的脚本,我需要用一个单独的循环产生的不同内容替换每次出现的标记。
使用 str_replace 将所有出现的标记替换为 相同 内容很简单,但我需要将每个出现替换为循环的下一个结果。
我确实看到了这个答案:Search and replace multiple values with multiple/different values in 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.
为了论证,我需要通过这个简单的循环将每次出现的 %%token%% 替换为生成的内容:
for($i=0;$i<3;$i++){
$token = rand(100,10000);
}
因此将每个 %%token%% 替换为不同的随机数值 $token。
这是我没有看到的简单东西吗?
谢谢!
【问题讨论】:
-
我认为没有库函数可以为您执行此操作。您只需编写搜索代码并自己替换即可。
-
我知道,我正在寻求帮助。我一直无法解决这个问题。我的 preg_replace 技能不是很好,但我发现了一些看起来很有帮助的东西,但我不知道如何根据需要修改它: $string = 'Time for some foo, because it is foo we want and foo我们将得到。是时候来点 foo 了,因为我们想要的是 foo,我们会得到 foo。'; $replaceme = 'foo'; $replacewith = '酒吧'; $n次 = 2; echo preg_replace("/((.*?)(".$replaceme.")){".$nthtimes."}/e", '(preg_replace("/".$replaceme."$/", "" , "\0")).$replacewith', $string);
-
抱歉,误解了这个问题。见答案。
标签: php string replace str-replace