Created
July 25, 2013 20:19
-
-
Save betweenbrain/6083354 to your computer and use it in GitHub Desktop.
Recursively trim non-alphanumeric characters from the end of a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $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 |
Author
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.
Yep, I was going to say just do it in one regex like @weierophinney suggests. No need to make it any more complicated.
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
I suppose
$length = $length - 1;could be--$length;