substr vs regex

Abigail abigail at
Mon Sep 3 10:44:53 BST 2007

On Mon, Sep 03, 2007 at 10:26:12AM +0100, alex at wrote:
> Imagine, say, someone wanted the last three characters of a string. They
> might use a regex /(...)$/ or substr($variable, -3)
> personally I recommend the former because it is more readable, but others
> have recommended substr to because you "dont need to bring out the big
> guns". (However no one could actually remember the substr function)
> Is one of these significantly more efficient than the other? Ok ok, so I
> could probably write a test in a few minutes but asking you guys is more
> interesting.

substr() is far more efficient than using a regexp. The speed of the
substr() solution is independent of the length of $variable, unlike the
regex solution. But even on a three character string, the difference
is measurable.

Of course, unless you're doing this hundreds of thousands of times, 
or have very long strings to deal with, noone will notice the difference.


More information about the mailing list