Search code examples
phpstringreplacewords

replace 2 words in a string with php


How can I do this replace in php, I have a first title which is like this:

the price From example To example is 3,

and I want to output the same title also but change like this:

the price To example From example is 3,

I use the code below but is not change the second word. I get this:

the price To example To example is 3,

echo str_replace(array("From","To"), array("To","From"), $title);


Solution

  • You want strtr:

    $newTitle = strtr($title, array("From"=>"To", "To"=>"From"));