gevans Posted October 30, 2009 Share Posted October 30, 2009 Hey guys, I use an easy regex with preg_replace to remove non alphanumeric characters from strings (using for URLs); <?php $string = "Here! is some text, and numbers 12345, and symbols !£$%^&"; $new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string); echo $new_string; This works fine, but it can often lead to double white spaces... here two spaces. Can I add anything simple to the regex to remove any leftover double (or more) white spaces? Cheers, gevans Quote Link to comment Share on other sites More sharing options...
cags Posted October 30, 2009 Share Posted October 30, 2009 You could run a second preg_replace... preg_replace("/[ ]{2,}/", " ", $string) ...you could obviously just add the match and replacements to arrays and run them in one call to preg_replace. Quote Link to comment Share on other sites More sharing options...
gevans Posted October 30, 2009 Author Share Posted October 30, 2009 Cheers cags, that's roughly what I'm doing at the moment. Can't think of a way to add it all in one regex. Also, it's only run when new pages are added so not a huge issue if I do continue to run two preg_replace's Quote Link to comment Share on other sites More sharing options...
cags Posted October 30, 2009 Share Posted October 30, 2009 You can do it in one call by using... $patterns = array("/[^a-zA-Z0-9\s]/", "/[ ]{2,}/"); $replacements = array("", " "); echo $output = preg_replace($patterns, $replacements, $input); You can't however do it in one pattern because the patterns match and replace different things. Edit: BTW \s will match whitespaces characters not just spaces, so it will allow tabs and line breaks. Quote Link to comment Share on other sites More sharing options...
gevans Posted October 30, 2009 Author Share Posted October 30, 2009 Thanks for that. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.