preg_match for alphanumeric

Hi,

I’m trying to test that $pm_user does not contain anything other than letters or numbers a-z A-Z 0-9

I put the followiing code but it doesn’t ever seem to set $pm_good_login to 0

$pm_good_for_login = 1
if (!preg_match(‘/[1]/’,$pm_user)):
$pm_good_for_login = 0 ;
endif ;

TIA

Pat


  1. a-zA-Z0-9 ↩︎

Hi Pat,

You need to add a + to the end of your regex pattern, like this:

preg_match('/^[a-zA-Z0-9]+/', $pm_user)

This means ‘match the preceding pattern one or more times’.

I’d be inclined to use the ctype_alnum() function instead of regex seen as it isn’t really necessary in this instance. Its usage is simple: it returns TRUE if all characters are alphanumerical, or FALSE if they’re not.

In order for your pattern to be reliable, you’ll need to use the $ anchor at the end of the pattern to ensure that the whole string contains only numbers and letters.

ctype_alnum()

Much easier , Thanks