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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?