简体   繁体   中英

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);

你想要strtr

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

Try this.

$phrase  = "the price From example To example is 3";
$texta = array("From", "To");
$textb   = array("To", "From");

$newphrase = str_replace($texta, $textb, $phrase);

So the problem is that str_replace will execute its replacing in order with your array and no matter what order you put them in it will always override the first replacement.

First step is you are telling str_replace to find " From " and replace with " To ". Making your phrase at this point:

the price From example To example is 3

which becomes

the price To example To example is 3

Then str_replaces to the next item in your array which is to look for "To" and replace it with "From". At this point you can probably see the problem.


Use ChrisMoll's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM