Re: validating input

From: Date: Wed, 13 Apr 2005 02:40:49 +0000
Subject: Re: validating input
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-212978@lists.php.net to get a copy of this message
On 12 Apr 2005 blackwater dev wrote: > $good = "joh_'"; > > // Let's check the good e-mail > if (preg_match("/[a-z0-9]/", $good)) { > echo "Good"; > } else { > echo "Bad"; > } > > This returns Good, why? That regex matches any string which contains at least one (lowercase) letter or one number somewhere within it. To match for only those elements and no others you probably want: if (preg_match("/^[a-z0-9]*$/", $good)) { which will match a string which contains nothing but a-z and 0-9, and will also match the empty string. See http://www.php.net/manual/en/reference.pcre.pattern.syntax.php and look at the meanings of ^, $, *, and +. Other variations for the regex: /^[a-z0-9]+$/ as above but will not match empty string /^[a-z0-9]*$/i as above but matches upper case as well /^[a-zA-Z0-9]*$/ like previous line -- as above but matches upper case as well As Chris S. pointed out, a regex is not needed for this task, so the above is just academic. -- Tom

« previous php.general (#212978) next »