Skip to content

Instantly share code, notes, and snippets.

@betweenbrain
Created July 25, 2013 20:19
Show Gist options
  • Select an option

  • Save betweenbrain/6083354 to your computer and use it in GitHub Desktop.

Select an option

Save betweenbrain/6083354 to your computer and use it in GitHub Desktop.
Recursively trim non-alphanumeric characters from the end of a string.
$string = "Mary had a little lamb :#$";
$length = strlen($string);
$regex = "/[^a-z0-9]/i";
for ($i = 1; $i <= $length; $i++) {
if (preg_match($regex, substr($string, $length - 1, 1))) {
$string = substr($string, 0, $length - 1);
$length = $length - 1;
} else {
break;
}
}
echo "Looped $i times. Result: " . $string;
// Looped 5 times. Result: Mary had a little lamb
@betweenbrain
Copy link
Copy Markdown
Author

I suppose $length = $length - 1; could be --$length;

@weierophinney
Copy link
Copy Markdown

Why not just:

$string = preg_replace('/[^a-z0-9]+$/i', '', $string);

The above finds sequences of non alpha-numeric characters at the end of a string, and removes them. No need to loop, when PCRE takes care of it for you.

@davereid
Copy link
Copy Markdown

Yep, I was going to say just do it in one regex like @weierophinney suggests. No need to make it any more complicated.

@betweenbrain
Copy link
Copy Markdown
Author

Awesome, thanks! It seems the magic bit I was missing was +$. Looks like I have a bit of PCRE studying to do. Thanks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment