TrueColors Posted November 15, 2010 Share Posted November 15, 2010 I want to allow Alphabetical strings, Numeric strings, and Alphanumeric strings. For example "Bob", "1234", "bob1234" are all valid. I want to check if the string has invalid characters, return true if it does (or false, which ever method works). How can I do it? Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/ Share on other sites More sharing options...
requinix Posted November 15, 2010 Share Posted November 15, 2010 ctype_alnum is your friend. Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/#findComment-1134250 Share on other sites More sharing options...
btherl Posted November 15, 2010 Share Posted November 15, 2010 You can probably get away with this: if (ctype_alnum($string)) { # Yes, all alpha or numeric } Do be aware that an empty string will match because it doesn't contain any characters that are not alphanumeric, so if you don't want empty strings you'll need to check for them seperately. Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/#findComment-1134251 Share on other sites More sharing options...
TrueColors Posted November 15, 2010 Author Share Posted November 15, 2010 New function to add to me list! Thanks! Would this function return true if we had "some string" (notice the space) ? Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/#findComment-1134252 Share on other sites More sharing options...
btherl Posted November 15, 2010 Share Posted November 15, 2010 It would return false. If you want a custom character set you can do it a few ways.. one is like this: if (preg_match('|^[a-zA-Z0-9 ]*$|', $string)) Meaning "If the string consists of any number of characters a-z A-Z 0-9 or space, then it's a match". Again, that will match empty strings. If you don't want empty strings you can change the * to a +, which means "one or more" Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/#findComment-1134254 Share on other sites More sharing options...
TrueColors Posted November 15, 2010 Author Share Posted November 15, 2010 Thanks! Link to comment https://forums.phpfreaks.com/topic/218687-check-if-a-string-has-invalid-characters/#findComment-1134255 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.