Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple string replace

Tags:

php

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.

like image 396
I-M-JM Avatar asked Mar 23 '11 05:03

I-M-JM


People also ask

How do I replace multiples in a string?

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."

How do I replace multiple characters in SQL?

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() .

How do you replace multiple strings in a list in Python?

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.


3 Answers

<?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.

like image 59
Prisoner Avatar answered Oct 20 '22 10:10

Prisoner


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

like image 22
diEcho Avatar answered Oct 20 '22 09:10

diEcho


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

like image 35
Daniel Kutik Avatar answered Oct 20 '22 11:10

Daniel Kutik