Home  >  Q&A  >  body text

Regular expression to validate numbers didn't work before I used

I want to use regex to validate my numbers before using them, but it didn't work.

I want the first number to start with 0, followed by 2 or 5, then 4, and the remaining numbers continue to 10 digits.

<?php
$str = "0241310102";
$pattern = "([0]{1}[2,5]{1}[4]{1}[0-9]{7})";

if(preg_match($pattern, $str)){
echo "YES";
}else{
echo "NO";
}

?>

P粉690200856P粉690200856423 days ago525

reply all(1)I'll reply

  • P粉329425839

    P粉3294258392023-09-14 13:05:30

    1. You need to anchor the pattern to the beginning/end of the string (^, $).
    2. Single numbers do not need to be specified as character classes[0]0
    3. Only needs to be specified when the quantifier is different from 1 0{1}0
    4. [2,5] will include commas in character classes → [25]
    $examples = [
        "0241310102",
        "1241310102",
        "0541310102",
        "0551310102",
        "0241"
    ];
    $pattern = '(^0[25]4[0-9]{7}$)';
    
    foreach ($examples as $example) {
        echo $example, ": ";
        if (preg_match($pattern, $example)) {
            echo "YES", "\n";
        } else {
            echo "NO", "\n";
        }
    }
    

    reply
    0
  • Cancelreply