Tag Archive for 'string'

PHP: speed of string replacement functions

What is the fastest string replacement function in PHP? sprintf() is probably the fastest, but it’s only useful in limited situations where the input is prepared for sprintf formatting. preg_replace() is obviously the slowest. The big debate is whether str_replace() or strtr() is faster.

The lixlpixel PHP benchmarks show that strtr is the faster of the two. I then came across Simple Machine’s benchmarks which show that str_replace() is faster. Hmm what’s going on?

Syridium DV’s PHP benchmarks performs more varied tests with these two functions. The relative speed of these two functions might vary depending on the type of string replacement you are performing. However, it seems that str_replace() is usually a safe bet.

If you liked this post, please subscribe to my feed. Thanks for visiting!

PHP: speed of string comparison functions

Here is a recent benchmark of various PHP string comparison functions. Not surprisingly, the fastest is strpos. But did you know that preg_match is faster than strstr and not much slower than strpos? This contradicts the following note in the official PHP manual:

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.

ereg is by far the slowest.

So, the best function to use to do a simple check to see if a string contains a particular substring is strpos. In all other cases preg_match might be superior to strstr. YMMV.