douji1999 2017-12-28 11:15
浏览 32

Preg_match不匹配

I'm trying to validate a Spanish phone number. I have a regular expression declared:

$telefono_regex = '/^(6|7|8|9)[0-9]{8}$/';

And I check the number:

if (!preg_match($telefono_regex, $telefono)){
     array_push($errores, 'telefono');
}

Why does this always return false? I have checked in https://regex101.com/ and found match with the same numbers.

  • 写回答

2条回答 默认 最新

  • dqxhit3376 2017-12-28 11:34
    关注

    The regex in your question and in your first try on regex101.com were different.

    Assuming you want to check numbers with optional dash or space every three digits(as in your first try on regex101.com), you can try this:

    $telefono_regex = '/^[6-9]{3}(?:[ -]?[0-9]{3}){2}$/';
    
    • ^[6-9]{3}: three digits from 6 to 9
    • (?:[ -]?[0-9]{3}): non-capturing group to match zero or one space or dash ([ -]?) followed by three numbers ([0-9]{3})
    • {2}: to match 2 occurrences of the non-capturing group

    You can check it here.

    评论

报告相同问题?

悬赏问题

  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题