PHP Regex在同一行上单独匹配模式

时间:2015-07-31 07:27:16

标签: php regex string preg-match preg-match-all

我正在尝试使用php regex解析文本。我写了一个符合一切的模式匹配。我不想要这个。它必须在同一行上单独匹配目标

模式:

/\((?P<type>\w+)((,)*(?P<params>[\d\w\:]+))((,)*(?P<comment>.*))\)/u

目标数据字符串:

lorem ipsum dolor (photo,61) test (photo,62,some text) (video,63) sit amet etc

结果preg_match_all与PREG_SET_ORDER标志:

array (size=1)
0 => 
    array (size=11)
      0 => string '(photo,61) test (photo,62,some text) (video,63)' (length=47)
      'type' => string 'photo' (length=5)
      1 => string 'photo' (length=5)
      2 => string ',61' (length=3)
      3 => string ',' (length=1)
      'params' => string '61' (length=2)
      4 => string '61' (length=2)
      5 => string ') test (photo,62,some text) (video,63' (length=37)
      6 => string '' (length=0)
      'comment' => string ') test (photo,62,some text) (video,63' (length=37)
      7 => string ') test (photo,62,some text) (video,63' (length=37)

如果目标数据放在单独的行中并且相同的正则表达式模式执行结果; (我想要这些结果但没有新行)

lorem ipsum dolor 
(photo,61) test 
(photo,62,some text) 
(video,63) sit amet etc

array (size=3)
    0 => 
        array (size=11)
          0 => string '(photo,61)' (length=10)
          'type' => string 'photo' (length=5)
          1 => string 'photo' (length=5)
          2 => string ',61' (length=3)
          3 => string ',' (length=1)
          'params' => string '61' (length=2)
          4 => string '61' (length=2)
          5 => string '' (length=0)
          6 => string '' (length=0)
          'comment' => string '' (length=0)
          7 => string '' (length=0)
      1 => 
        array (size=11)
          0 => string '(photo,62,some text)' (length=20)
          'type' => string 'photo' (length=5)
          1 => string 'photo' (length=5)
          2 => string ',62' (length=3)
          3 => string ',' (length=1)
          'params' => string '62' (length=2)
          4 => string '62' (length=2)
          5 => string ',some text' (length=10)
          6 => string ',' (length=1)
          'comment' => string 'some text' (length=9)
          7 => string 'some text' (length=9)
      2 => 
        array (size=11)
          0 => string '(video,63)' (length=10)
          'type' => string 'video' (length=5)
          1 => string 'video' (length=5)
          2 => string ',63' (length=3)
          3 => string ',' (length=1)
          'params' => string '63' (length=2)
          4 => string '63' (length=2)
          5 => string '' (length=0)
          6 => string '' (length=0)
          'comment' => string '' (length=0)
          7 => string '' (length=0)

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

只需使用

'~\(.*?\)~'

并且它已经完成

Regex101 Eval

答案 1 :(得分:0)

我找到了一个不受新行影响的解决方案(根本解决方案是附上“〜...〜”不使用“/.../")

~\((\w+),([\d|:]+),*(.*?)\)~u

命名版本;

~\((?P<type>\w+),(?P<params>[\d|:]+),*(?P<comment>.*?)\)~u

感谢@Uchiha预解决方案并感谢您提供的提示。

'~\(.*?\)~'