how do you give different names to str_replace words?

52 Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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
0
On

Take a look preg_replace.

A pattern could be #car\d+#i

1
On

Alright I came up with this:

<?php
$numberofwords=substr_count($text,'car');
for($i=1;$i<=$numberofwords;$i++)
{
    $text=preg_replace('/car/','car'.$i,$text,1);
}
?>

and it seems to work :) thanks all