Khoo Wing Hang Khoo Wing Hang - 1 month ago 18
PHP Question

preg match for digits and alphabet

I'm making

preg_match
that allows 7-10 digits.

preg_match('/[0-9]{7,10}/', $studentID


Also another
preg_match
code that allows maximum of 20 alphabets with space and hyphen.

preg_match ('/^[a-zA-Z -]{,20}+$/i', $familyname


Both of these are not working.

Answer

You need to add anchors to the first regex the same way you used them with the second pattern, and you must define the lower bound for the limiting quantifier in the second pattern (say, 0 to 20):

$studentID = "1234567";
if (preg_match('/^[0-9]{7,10}$/', $studentID)) {
    echo "$studentID matched!\n";
}
$familyname = "Pupkin";
if (preg_match ('/^[A-Z -]{0,20}$/i', $familyname)) {
    echo "$familyname matched!";
}

See the PHP demo

Note that {0,20} and its possessive {0,20}+ version will work the same here since the pattern is not followed with other consuming subpatterns (so, no need to disable backtracking for the quantified subpattern).

Also, '/^[A-Z -]{0,20}$/i' is a very generic subpattern for surnames, you might want to further precise it. E.g., to disallow strings like all spaces or ---------, you may use '/^(?=.{0,20}$)[A-Z]+(?:[ -][A-Z]+)*$/i'.

Comments