Jump to content

Check if a string has invalid characters


TrueColors

Recommended Posts

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?

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.

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"

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.