How to replace multiple items from a text string in PHP? [duplicate]

You can pass arrays as parameters to str_replace(). Check the manual. // Provides: You should eat pizza, beer, and ice cream every day $phrase = “You should eat fruits, vegetables, and fiber every day.”; $healthy = [“fruits”, “vegetables”, “fiber”]; $yummy = [“pizza”, “beer”, “ice cream”]; $newPhrase = str_replace($healthy, $yummy, $phrase);

How to replace multiple values in php

This should work for you: <?php $string = “test1 test1 test2 test2 test2 test1 test1 test2”; echo $string . “<br />”; echo $string = strtr($string, array(“test1” => “test2”, “test2” => “test1”)); ?> Output: test1 test1 test2 test2 test2 test1 test1 test2 test2 test2 test1 test1 test1 test2 test2 test1 Checkout this DEMO: http://codepad.org/b0dB95X5

swap two words in a string php

Use strtr From the manual: If given two arguments, the second should be an array in the form array(‘from’ => ‘to’, …). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been … Read more

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. // Outputs F because A is replaced with B, then B is replaced with C, and so on… // Finally E is replaced with F, because of left to right replacements. $search = array(‘A’, ‘B’, ‘C’, ‘D’, ‘E’); … Read more

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal. str=xpath.replaceAll(“\\.”, “/*/”); //replaces a literal . with /*/ http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)