poe Posted October 19, 2007 Share Posted October 19, 2007 lets say i have these 3 values in an array: Bath & Body Handbags Home Accents i want to remove all non alpha characters like ' '(space) and the '&'(amp sign) and replace with a single '_' (underscore). regardless of how many characters i remove i want to replace with just 1 '_' so my example would look like: Bath_Body Handbags Home_Accents Quote Link to comment https://forums.phpfreaks.com/topic/73906-remove-non-alpha-characters-from-string/ Share on other sites More sharing options...
corbin Posted October 19, 2007 Share Posted October 19, 2007 $string = 'Bath & Body'; echo preg_replace('/[^a-zA-Z0-9]+/', '_', $str); Try that. Quote Link to comment https://forums.phpfreaks.com/topic/73906-remove-non-alpha-characters-from-string/#findComment-372933 Share on other sites More sharing options...
pocobueno1388 Posted October 19, 2007 Share Posted October 19, 2007 <?php $string = "Home Accents"; $new_string = preg_replace("/[^a-zA-Z0-9s]/", "_", $string); echo $new_string ?> I was beat to it, but if that one doesn't work, here is another example. Quote Link to comment https://forums.phpfreaks.com/topic/73906-remove-non-alpha-characters-from-string/#findComment-372935 Share on other sites More sharing options...
corbin Posted October 19, 2007 Share Posted October 19, 2007 pocobueno, I'm pretty bad at regular expressions, so there's a great chance I'm wrong, but I think that would just replace each non alpha numeric character with _.... Meaning Bath & Body would be Bath___Body. Also, what's with the s? Once again, I'm terrible at regular expressions x.x Quote Link to comment https://forums.phpfreaks.com/topic/73906-remove-non-alpha-characters-from-string/#findComment-372940 Share on other sites More sharing options...
pocobueno1388 Posted October 19, 2007 Share Posted October 19, 2007 pocobueno, I'm pretty bad at regular expressions, so there's a great chance I'm wrong, but I think that would just replace each non alpha numeric character with _.... Meaning Bath & Body would be Bath___Body. Also, what's with the s? Once again, I'm terrible at regular expressions x.x I didn't do that regular expression myself, I found it on a site and tested it. I'm pretty sure the "s" is for white spaces though. Ah, your right about it returning "Bath___Body". I didn't take into account this part of the post: "regardless of how many characters i remove i want to replace with just 1 '_'". Quote Link to comment https://forums.phpfreaks.com/topic/73906-remove-non-alpha-characters-from-string/#findComment-373139 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.