phpcodec Posted October 28, 2008 Share Posted October 28, 2008 How can i write a regex that will check for any characters that are not in the list below and return true if any unknown characters are found a-z A-Z 0-9 _ (under-dash) - (hypen) (space) Quote Link to comment https://forums.phpfreaks.com/topic/130403-remove-special-characters/ Share on other sites More sharing options...
MadTechie Posted October 28, 2008 Share Posted October 28, 2008 $text = preg_replace('/[^a-zA-Z0-9_ -]/s', '', $text); or i shorter version $text= preg_replace('/[^\w\d_ -]/si', '', $text); EDIT: the above is a clean up heres to match <?php if (preg_match('/[^\w\d_ -]/si', $text)) { echo "found unknown characters"; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/130403-remove-special-characters/#findComment-676403 Share on other sites More sharing options...
discomatt Posted October 28, 2008 Share Posted October 28, 2008 I believe underscore is already matched in the \w shorthand so you could make it even shorter Quote Link to comment https://forums.phpfreaks.com/topic/130403-remove-special-characters/#findComment-676611 Share on other sites More sharing options...
MadTechie Posted October 28, 2008 Share Posted October 28, 2008 Doh!... very true Quote Link to comment https://forums.phpfreaks.com/topic/130403-remove-special-characters/#findComment-676618 Share on other sites More sharing options...
nrg_alpha Posted October 28, 2008 Share Posted October 28, 2008 Depending on locale, \w *might* match additional characters such as à ò ì ù è. Something to consider. Also, \d can match more than simply 0-9 (example: 0¹²³4). However, I'm not sure if this is locale dependent or not. So depending on what string content is being checked, there may be some pitfalls if one is not careful. Quote Link to comment https://forums.phpfreaks.com/topic/130403-remove-special-characters/#findComment-676753 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.