[thelist] PHP: is_numeric... that's the question...

KrisG thelist at charitycards.co.uk
Thu Jan 18 08:44:05 CST 2007


Tris,
         the pattern ![a-zA-Z]{2}[0-9]{5}! would be happy with 
999-AB12345-XYZ as it matches the two alpha and 5 numeric string in the middle.
         It needs to be told that the string should start with 2 
alpha (^[a-zA-Z]{2}) ( ^ means match at the beginning of the string) 
and have 5 numeric at the end ([0-9]{5}$) where the '$' means match 
this at the end of the string.

I'm not 100% sure if this matched only 7 characters, or if it may 
pass [TwoAlpha]anythingElseHere[FiveNumeric], but it seems to be 
reporting no (or at least 'less') false positives than without the 
beginning and end string stipulations.
so..........

function check($usercode){
         $pattern = '!^[a-zA-Z]{2}[0-9]{5}$!'; // note the ^ at the 
beginning and $ at the end
         return preg_match($pattern,$usercode);
}

btw. The error in the original logic was that it failed on the 
is_numeric on A7 as well as AA, as neither are decimally numeric.

Kris

At 18:41 17/01/2007, you wrote:

>I must be blind, because I don't see the error in your code.  However, I
>it might be easier --both to read and to debug-- to use a simple regex here.
>
>function check($usercode) {
>         /* valid pattern is 2 letters followed by 5 digits */
>         $pattern = '![a-zA-Z]{2}[0-9]{5}!';
>         return preg_match($pattern, $usercode);
>}
>
>//example
>$codes = array('F454354','4G64345','AA12345');
>foreach($codes as $c) {
>echo "$c is ".(check($c) ? 'valid': 'invalid')."<br>";
>}





More information about the thelist mailing list