I've been using this code for awhile to shorten URLs that are posted by users:
if (length($_) > 45) {
# converts this:
# https://www.example.com/whatever.html?something=abc
# to this
# https://www.example.com/wha...ething=abc
$_ = substr($_, 0, 27) . '...' . substr($_, -10);
}
I already check to make sure that it's a proper link before this, so there's no real need to check it here. It has 3 built-in commands: length(), and then two iterations of substr().
As an alternative, I COULD do:
# reads as, find exactly 27 characters, followed by 5 or more characters,
# followed by exactly 10 characters, then replace the 5 or more with ...
s#([^\s]{27})[^\s]{5,}([^\s]{10})#$1...$2#i;
This variation is a regex, which is traditionally slower, but is it slower than 3 commands combined?
Of course, I know that we're probably talking microseconds here. But this is really just for my own education. Over the years I've followed the "use regex only as a last resort" guideline, but I recently realized in PHP testing that sometimes it's faster than using multiple built-in commands. So while I'm rebuilding anyway, why not shave microseconds where I can?