str_replace在找到它时多次替换相同的字符串

时间:2015-02-23 21:13:04

标签: php string

我正在尝试用其他字符串替换数组中的某些字符串,只是如果PHP intepretor再次找到相同的字符串,它将应用值替换为tp相同的字符串,就像字符串在数组中一样多次。例如:

$html = 'first
         first
         second
         third
         third';
$array = array('first', 'first', 'second', 'third', 'third');
foreach ($array as $elem) {
  $html = str_replace($elem, $elem.' | added', $html);
}
var_dump($html); //will result

string 'first | added | added

             first | added | added

             second | added

             third | added | added

             third | added | added' (length=158)

预期输出

string 'first | added

             first | added

             second | added

             third | added

             third | added' (length=158)

1 个答案:

答案 0 :(得分:3)

尝试preg_replace

foreach($array as $elem) {
    $html = preg_replace("/$elem(?! \| added)/", "$0 | added", $html);
}

如果每个项目都没有| added,则替换它们。您可以使用$elem代替$0。可能有一个更好的正则表达式,但我是中间人而不是巫师。