stripping end characters from strings in PHP

I’ve been doing some updates to my URL shortening service (sqwi.sh) recently, and some functionality I needed was to remove the last 2 characters of a string. Now, the normal way to remove the last character of any given string (as taught most places) is:

$str = substr($str,0,strlen($str)-1);

But, I was feeling like being out of the ordinary. After a bit of a rummage around, and some lateral/creative thinking, I came up with the following:

$string =  strrev(substr(strrev($string), 2));

I’ll break it down a bit below:

// first of all, reverse the string
// so, "thisIsAString" becomes "gnirtSSsIsiht"

$string = strrev($string);

// now, get the substring starting at the 3rd character
// so, "gnirtSSsIsiht" becomes "irtSSsIsiht"

$string = substr($string, 2);

// now, reverse the string again
// so, "irtSSsIsiht" becomes "thisIsAStri"

$string =  strrev($string); 

You can change the ‘2’ to be however many characters you wish to remove from the end of the string.

The one using strrev() is a lot faster then the ‘normal’ one for larger strings or many strings as it doesn’t require the script to count it’s way to the end of the string, but the first way is absolutely valid and works equally well so I would be remiss to not mention it.

Advertisements

About Cameron
I'm a final year Computer Science/Information Systems major. Already finished my BA in Politics/Philosophy. I do web and software freelance on the side, while I finish studying. Hoping to be self-employed by the end of my degree, otherwise off into the real-world I go....

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: