How to create a list of allowed characters

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
strategos
Forum Newbie
Posts: 4
Joined: Thu Jul 28, 2011 4:15 pm

How to create a list of allowed characters

Post 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" );
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: How to create a list of allowed characters

Post 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...
}
Post Reply