Saturday, September 8, 2007

str_replace - strtr

This two functions are too similar. Usually, str_replace is more famous, but which one is better? Let's try...

str_replace('e','a','hello world');
strtr('hello world','e','a');

Let's compare a simple replace. In this comparison, str_replace takes a point.

What happens if it is wanted to replace a text that is not?
Both functions are quicker, but str_replace still more optimal. At this instance, it seems this options is better, but both functions allows multiple replacements at a time. Let's try it.

str_replace(array('o','e'),'a','hello world');
strtr('hello world',array('o' => 'a','e' => 'a'));

Here we reeplace "o" and "e" for "a", and str_replace still likes better... Let's give strtr a las chance

str_replace(array('o','e'),array('i','o'),'hello world');
strtr('hello world',array('o' => 'i','e' => 'o'));

In this case, the replacements are 'o' for 'i', and 'e' for 'a', and surprisely strtr takes the victory.

Conclusion: usually, its preferable to use str_replace, but when you want to replace many characters for many others characters (and not only a value) strtr is better.

View example

1 comment:

Anonymous said...

str_replace is more faster that strtr