dougan6982 2013-09-17 07:28
浏览 129
已采纳

为什么我的PHP preg_match匹配第二个子模式而不是第一个?

My PHP code is:

$pattern = '/(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(,| )[\d]{1,2}[A-Z]{1,1}[a-z]{2,2}/';
if (preg_match($pattern, $content, $matches, PREG_OFFSET_CAPTURE)){
    $name = str_replace("(M1) ", "", substr($content, 0, $matches[0][1]));
    $date = substr($content, $matches[0][1], 15);
}

It works fine with one match sub pattern.Like:

  
B'Meadow Alarm Tue,17Sep 19:48 Ur001 General User Closing By User 
name:  B'Meadow Alarm  
date:  Tue,17Sep 19:48

My string is:

(M1) B'Meadow Alarm Tue,17Sep 19:48 Ur001 General User Closing By User (M2) B'Meadow Alarm Tue,18Nov 09:18 Ur001 General User Closing By User

it is supposed to be:

name:  B'Meadow Alarm  
date:  Tue,17Sep 19:48

But the reality result is:

name:  B'Meadow Alarm Tue,17Sep 19:48 Ur001 General User Closing By User (M2) B'Meadow Alarm  
date:  Tue,18Nov 09:18  

Question: What is wrong in my pattern? or code?

----------

Edit

Sorry, guys! One of my colleague changed this regular expression on Server's repository to following one:
'/(.*)(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(,| )[\d]{1,2}[A-Z]{1,1}[a-z]{2,2}(.*)/';

But he doesn't commit to git. That is why I can't see these changes in my local repository. the (.*) cause the problem.

  • 写回答

1条回答 默认 最新

  • duanjiwu0324 2013-09-17 07:38
    关注

    Neither of your pattern or code is wrong. Your code output exactly as supposed to be.

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

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题