Regular expression to validate numbers didn't work before I used
P粉690200856
P粉690200856 2023-09-13 15:00:59
0
1
560

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粉690200856
P粉690200856

reply all(1)
P粉329425839
  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";
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template