我想在使用数字之前使用正则表达式验证它,但它不起作用。

huangapple go评论59阅读模式
英文:

I want to validate my numbers with regex before using it but it not working out

问题

I want to validate my numbers with regex before using it but it not working out

I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit

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

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

?>
英文:

I want to validate my numbers with regex before using it but it not working out

I want the first digit to start with 0 follow by 2 or 5 and follow by 4 and the rest continue to 10 digit

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

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

?&gt;

答案1

得分: 1

  1. 你需要将模式锚定到字符串的开头/结尾(^$)。
  2. 单个数字不需要被指定为字符类 [0]0
  3. 量词只需要在与1不同的情况下指定 0{1}0
  4. [2,5] 会包含字符类中的逗号 → [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";
    }
}
英文:
  1. You need to anchor the pattern to the start/end of the string (^, $).
  2. Single digits do not need to be specified as a character class [0]0
  3. Quantifier need only to be specified if different from one 0{1}0
  4. [2,5] would include the comma in the character class → [25]
$examples = [
    &quot;0241310102&quot;,
    &quot;1241310102&quot;,
    &quot;0541310102&quot;,
    &quot;0551310102&quot;,
    &quot;0241&quot;
];
$pattern = &#39;(^0[25]4[0-9]{7}$)&#39;;

foreach ($examples as $example) {
    echo $example, &quot;: &quot;;
    if (preg_match($pattern, $example)) {
        echo &quot;YES&quot;, &quot;\n&quot;;
    } else {
        echo &quot;NO&quot;, &quot;\n&quot;;
    }
}

huangapple
  • 本文由 发表于 2023年6月29日 00:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定