Search code examples
phpstr-replacewords

how do you give different names to str_replace words?


I have a piece of text, and I want to replace every word for example "car" with car and a number so: "car1", "car2", "car3" etc with PHP

I tried using str_replace(); but to no avail.

<?php
$text='yadadyayayay car yayayaya car aksdkjasd car car car car car car car';
$output=str_replace('car','car'.$count,$text,$count);
echo $output;
?>

I come to think str_replace() may not be the right approach.

Thank you very much.


Solution

  • Here is my solution

        $findStr = 'car';
        $str = 'yadadyayayay car yayayaya car aksdkjasd car car car car car car car';
    
        $count = substr_count($str, $findStr);
    
        $str = preg_replace("/$findStr/", "$findStr ", $str);
        for($i=1; $i <= $count; $i++)
        {
            $str = preg_replace("/$findStr\D/", $findStr . $i, $str, 1);
        }
    
        echo $str;
    

    This will output

    yadadyayayay car1 yayayaya car2 aksdkjasd car3 car4 car5 car6 car7 car8 car9