str_replace查找字符串时多次替换相同的字符串


str_replace Replacing same occurence of string as many times as it founds it

我正试图用其他字符串替换数组中的一些字符串,只是如果PHP编译器再次找到相同的字符串,它将应用这些值来替换为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)

尝试preg_replace:

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

如果后面没有| added,则替换每个项目。您可以使用$elem而不是$0。可能有一个更好的正则表达式,但我是中级而不是向导。