I need to replace multiple text with it's associated text
Example: I have string like: "apple is a great fruit"
Now I need to replace "apple"
to "stackoverflow"
, and "fruit"
to "website"
I know I can use str_replace
, but is there any other way? str_replace
would be slow in my case, because I need to replace atleast 5 to 6 words
Help appreciated.
replace(/cat/gi, "dog"); // now str = "I have a dog, a dog, and a goat." str = str. replace(/dog/gi, "goat"); // now str = "I have a goat, a goat, and a goat." str = str. replace(/goat/gi, "cat"); // now str = "I have a cat, a cat, and a cat."
If you wanted to replace the words with blank string, go with REGEXP_REPLACE() . If you want to replace the words with other words, for example replacing & with and then use replace() . If there are multiple words to be replaced, use multiple nested replace() .
There is no method to replace multiple different strings with different ones, but you can apply replace() repeatedly. It just calls replace() in order, so if the first new contains the following old , the first new is also replaced.
<?php
$a = array('cheese','milk');
$b = array('old cow','udder');
$str = 'I like cheese and milk';
echo str_replace($a,$b,$str); // echos "I like old cow and udder"
Alternatively, if you don't like to look of that (worried of miss matching array values) then you could do:
$start = $replace = $array();
$str = "I like old cow and udder"
$start[] = 'cheese';
$replace[] = 'old cow';
$start[] = 'milk';
$replace[] = 'udder';
echo str_replace($start,$replace,$str); // echos "I like old cow and udder"
edit: I see dnl has edited the question and put emphasis on the fact that str_replace would be too slow. In my interpretation of the question it is because the user was not aware that they would use arrays in str_replace.
if u know all the word sequence and also replaced word then use below technique
$trans = array( "apple" => "stackoverflow", "fruit" => "website");
echo strtr("apple is a great fruit", $trans); // stackoverflow is a great website
Reference
For your purpose str_replace
seams to be already the fastest solution.
str_replace
is faster than strstr
Source: http://www.simplemachines.org/community/index.php?topic=175031.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With