duansao6776 2015-05-30 17:44
浏览 31
已采纳

PHP正则表达式错误

I am new to PHP regex. I've written below code, but there is something wrong. Could someone please suggest to me what is going wrong?

Code Link

Input:

    1 => 'String',
    2 => 'String String',
    3 => 'email',
    4 => 'date',
    5 => 'date',
    6 => 'String String',
    7 => 'String String',
    8 => 'String',
    9 => 'date'

Here is the same code from above link:

<?php 
    $text = "john123 john william johnw@hotmail.com 2015-05-09 13:21:41 2015-08-07 13:21:41 James James William William group1 2015-05-30 18:05:39"; 

    $regex = '~([a-zA-Z]+) ([a-zA-Z]+ [a-zA-Z]+) ([-\w.+]+@[-\w.+]+\.[a-zA-Z]{2,4}) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([a-zA-Z]+ [a-zA-Z]+) ([a-zA-Z]+ [a-zA-Z]+) ([a-zA-Z]+) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})~i';

    if ( preg_match( $regex, $text ) ) {
         echo $text . " is a valid text. We can accept it.";
    } else { 
         echo $text . " is an invalid text. Please try again.";
    } 

?>
  • 写回答

1条回答 默认 最新

  • dongyong5255 2015-05-30 17:55
    关注

    In your test string john123 and group1 has digits which you are trying to match with [a-zA-Z]+ make them [a-zA-Z\d]+ and also other groups where digits are possible.. Use the following:

    ([a-zA-Z\d]+) ([a-zA-Z]+ [a-zA-Z]+) ([-\w.+]+@[-\w.+]+\.[a-zA-Z]{2,4}) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) ([a-zA-Z]+ [a-zA-Z]+) ([a-zA-Z]+ [a-zA-Z]+) ([a-zA-Z\d]+) (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})
    

    Edit: Since you are already using i (case insentitive) modifier.. you can just have [a-z]+ for alphabet and [a-z\d]+ for alphanumeric characters.

    See DEMO

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答