dongliu0823 2015-04-28 15:07
浏览 23
已采纳

解密preg_match

I'm trying to fix some code written by another developer:

 $rexSafety = '@[0-9-\+\s\(\)]+$@';
 if (!preg_match($rexSafety, $_POST['phone'])) $spam = true;

When I type in an 11-digit number (UK standard phone length) without spaces or any other characters, the number (from $_POST['phone']) is marked as spam.

Unfortunately I don't know anything about regular expressions so I was hoping someone would be able to 'decipher' this and tell me what it is expecting?

01234567890 should be a match. It's currently not.

  • 写回答

2条回答 默认 最新

  • dsb53973 2015-04-28 15:24
    关注

    Here's the breakdown of your regex. I threw out the @ because he used those as boundary characters. Normally you would use something like / instead (note that's what regex101.com uses)

    [0-9-\+\s\(\)]+$
    

    [] indicates a character set we want to match. You put everything you want matched in here. A dash means you have a range so 0-9 will match all decimal numbers

    \ is the escape character. It means you want literal characters. So \+ is going to match + in your string

    \s is a special class that matches whitespace

    \(\) means you want to match any parenthesis ( or )

    $ is the end of your string (this is unnecessary since we want anything that matches)

    I tweaked it and this should do what you want

    if(preg_match('/([^0-9-\+\s\(\)])/', $_POST['phone'])) $spam = true;
    

    By adding ^ we tell regex we don't want anything from this class to match. I also wrapped it in parenthesis to make it a capturing group. That means it will grab the matching elements and return them

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图