dongzhen4180 2015-07-10 16:37
浏览 344
已采纳

使用RegEx限制字符串长度

I wrote this regex for checking the input number from my form:

if (!preg_match("/^0\d{10}+|^9\d{9}+/",$_POST['number'])){
   echo "Error";
}else{
   echo "Ok";
}

this code will check the minimum length but if length is more than 10 or 9 characters, this regex cannot work !

What should I do ? should I check with strlen after Regex or I can limit the maximum length ?

UPDATE:

the string length should be exactly 10 characters if start with 0 and should be exactly 9 characters if start with 9, and should return false on another ways (more or less length, start with different numbers and ...)

  • 写回答

2条回答 默认 最新

  • dongwu8064 2015-07-10 16:46
    关注

    Possibly you just want to anchor the string at the end using $. Also can drop the + after the numeric quantifier:

    ^(?:0\d{9}|9\d{8})$
    

    See test at regex101.com

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示