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
wou开发者_如何学Cld be slow in my case, because I need to replace atleast 5 to 6 words
Help appreciated.
<?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
精彩评论