douyuan4357 2015-11-08 18:53
浏览 7
已采纳

匹配2个正则表达式图案,正面或背面有1个图案

I have a regex that matches 2 patterns with 1 pattern in the front or back, but the first array return 2 empty indexes. Why is it doing that, and how would I stop it from doing that?

$text = "i did";
preg_match("~(?:(did) (.+)|(.+) (did))~", $text, $match);
print_r($match);

echo "<br>";

$text = "did i";
preg_match("~(?:(did) (.+)|(.+) (did))~", $text, $match);
print_r($match);

Result:

Array ( [0] => i did [1] => [2] => [3] => i [4] => did ) 
Array ( [0] => did i [1] => did [2] => i )

Want Result:

Array ( [0] => i did [1] => i [2] => did ) 
Array ( [0] => did i [1] => did [2] => i )
  • 写回答

2条回答 默认 最新

  • doukongpao0903 2015-11-08 19:17
    关注

    You can use a branch reset (?|...):

    Alternatives inside a branch reset group share the same capturing groups. The syntax is (?|regex) where (?| opens the group and regex is any regular expression.

    Your preg_match will look like:

    preg_match("~(?|(did) (.+)|(.+) (did))~", $text, $match);
    

    See IDEONE demo

    Results:

    Array
    (
        [0] => i did
        [1] => i
        [2] => did
    )
    

    I guess your regex is a sample one. If you need to match a word after or before did, use the \w shorthand class:

    preg_match("~(?|(did) (\w+)|(\w+) (did))~", $text, $match);
    

    See another demo

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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)