Page 1 of 1

How to create a list of allowed characters

Posted: Wed Jan 18, 2012 9:13 pm
by strategos
Hi, i'm a noob to PHP and this is a noob question ;)

Im trying to create a list of allowed characters so I can compare them with a string to return true or false

I know this is done wrongly, but how exactly would I do it? Would I use an array? Please help :D

Code: Select all

$test = ( "A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X","Y", "Z", "0-9" );

Re: How to create a list of allowed characters

Posted: Wed Jan 18, 2012 10:52 pm
by twinedev
If you are trying to see if the entire string contains only the set:

Code: Select all

if (preg_match('/^[A-Z0-9]+$/',$strTest)) {
  // Was good...
}
or

Code: Select all

if (!preg_match('/^[A-Z0-9]+$/',$strTest)) {
  // Was bad
}
If you want both upper and lower case...

Code: Select all

if (preg_match('/^[a-z0-9]+$/i',$strTest)) {
  // Was good...
}
Also, if you were to need the hyphen as part of valid characters, put it at the start or end:

Code: Select all

if (preg_match('/^[A-Z0-9-]+$/',$strTest)) {
  // Was good...
}