Skip to content
Advertisement

Php str_replace one by one in loop

I have a string like

A name Tokyo 26, B name Moscov 45, C name Newyork 26, D name Berlin 67, E name Paris 37, F name London 39

I want to replace name words as name1 name2 name3…. so the final string will be like

A name1 Tokyo 26, B name2 Moscov 45, C name3 Newyork 26, D name4 Berlin 67, E name5 Paris 37, F name6 London 39

How can I replace matching words each time with different value?

Advertisement

Answer

Try this , store it on array and join again

$str = 'A name Tokyo 26, B name Moscov 45, C name Newyork 26, D name Berlin 67, E name Paris 37, F name London 39';

$toReplace = 'name';
$count = explode(',',$str);
$array = array();
for($i = 0; $i < count($count); $i++) {
  $num = $i + 1;
  $array[] = str_replace($toReplace , $toReplace . $num , $count[$i]);
}

$new_str = implode(',',$array);
echo $new_str;

Output with :

A name1 Tokyo 26, B name2 Moscov 45, C name3 Newyork 26, D name4 Berlin 67, E name5 Paris 37, F name6 London 39

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement