Jump to content

Why does this matching fail?


vijdev

Recommended Posts

Better to do that check outside of regex:

 

$stringLen = strlen($string);
if ($stringLen < 1 || $stringLen > 20 || !preg_match("/[A-Za-z]*/",$input) ) {
    echo 'You have provided invalid input. Valid input ......'; 
}

 

Untested, pending any retarded errors I made should work for what you want.

Better to do that check outside of regex:

 

$stringLen = strlen($string);
if ($stringLen < 1 || $stringLen > 20 || !preg_match("/[A-Za-z]*/",$input) ) {
    echo 'You have provided invalid input. Valid input ......'; 
}

 

Untested, pending any retarded errors I made should work for what you want.

 

thanks, but would this solve my initial problem of not passing $#@$@ ?

What exactly do you want this regular expression to do? You want it to match alphabetic-characters at the beginning of a string? If so, it appears to be working fine for me:

<?php
$input='hjkhk$#@$@';
preg_match_all("/^[A-Za-z]{1,20}/",$input,$match);
print_r($match);
?>

 

produces:

Array
(
    [0] => Array
        (
            [0] => hjkhk
        )

)

Ok, Let me put again the problem definition for clarity:

 

1.I need to check if input is only alphabets, not one single other type character

2.Needs to be minimum 1 char and max 20 characters long

 

This is what am intending to do with above expression.Any directions?..have to admit it looks so simple! :|

Unless I am terribly mistaken, {1,20} means anywhere between 1 and 20 (inclusive) occurances of the preceeding class. In this case, your RegExp will match any string that starts with 1 or more alphabetic characters (upper or lower case) regardless of how long the string is.  It will match this entire paragraph. 

 

I think if you anchor the RegExp to the end of the string as well, then it will do what you are expecting:

 

$input='hjkhk$#@$@';
$test=preg_match_all("/^[A-Za-z]{1,20}$/",$input,$match);

 

The caret ( ^ ) anchors to the start of the string and the dollar-sign ( $ ) anchors to the end. So now it should match a string of 1 to 20 alphabetic characters.

 

I am no RegExp expert, not even a little bit.  But I think this is correct. Give it a go

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.