如何用数组替换字符串中的相同字符串实例?

时间:2011-02-01 14:38:18

标签: php

$replaces = array('replace 1', 'replace thing 2', 'third replace');

$string = '{REPLACEME} sfsfsdfsdf {REPLACEME} sdfopjsd {REPLACEME} sdfsdf {REPLACEME}';

使用匹配替换替换每个后续{REPLACEME}的最简单方法是什么?

如果{REPLACEME}比替换更多,则不应触及额外的{REPLACEME}

所以我想要的输出是:

replace 1 sfsfsdfsdf replace thing 2 sdfopjsd third replace sdfsdf {REPLACEME}

3 个答案:

答案 0 :(得分:8)

foreach($replaces as $rep) {
  $string = preg_replace('~\{REPLACEME\}~',$rep,$string,1);
}

答案 1 :(得分:2)

这可能是一个快速的想法:

$replaces = array('replace 1', 'replace thing 2', 'third replace');
$string = '{REPLACEME} sfsfsdfsdf {REPLACEME} sdfopjsd {REPLACEME} sdfsdf {REPLACEME}';
$sampler = explode('{REPLACEME}',$string);
foreach($sampler as $k=>$v){
 if(isset($replaces[$k])) {
     $sampler[$k] .= $replaces[$k]
 } else {
  $sampler[$k] = '{REPLACEME}' //or whatever
 }
}
$final = implode("",$sampler);
//it's ok for not so long strings or at least not to many {REPLACEME}

答案 2 :(得分:1)

Catalin Marin’s proposal类似,但无需检查是否有足够的替换字符串:

$parts = explode('{REPLACEME}', $string, count($replaces)+1);
for ($i=0, $n=count($parts); $i<$n; $i++) {
    $parts[$i] .= $replaces[$i];
}
$string = implode('', $parts);

如果您需要搜索的正则表达式,则可以使用preg_split代替explode

此解决方案的优势与连续多次调用str_replace / preg_replace相反:

  • $string仅在一次中搜索{REPLACEME}(最多只有count($replaces)
  • 如果
  • {REPLACEME}出现在先前替换$replaces中,则不会被替换。