PHP正则表达式组捕获

car*_*usm 14 php regex

我有以下正则表达式:

\[([^ -\]]+)( - ([^ -\]]+))+\]
Run Code Online (Sandbox Code Playgroud)

这成功匹配如下:

[abc - def - ghi - jkl]
Run Code Online (Sandbox Code Playgroud)

但比赛是:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - jkl
    [3] => jkl
)
Run Code Online (Sandbox Code Playgroud)

我需要的是这样的:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - def
    [3] => def
    [4] =>  - ghi
    [5] => ghi
    [6] =>  - jkl
    [7] => jkl
)
Run Code Online (Sandbox Code Playgroud)

我能够在C#中查看群组"捕获".我怎么能用PHP做到这一点?

Ama*_*dan 12

这不是正则表达式的工作.匹配\[([^\]]*)\],然后split第一次捕获" - ".

<?php                                                                       
  $str = "[abc - def - ghi - jkl]";
  preg_match('/\[([^\]]*)\]/', $str, $re);
  $strs = split(' - ', $re[1]);
  print_r($strs);
?>
Run Code Online (Sandbox Code Playgroud)


dru*_*dge 12

假设示例字符串中的标记从不包含空格,并且是字母数字:

<?php
    $pattern = "/([\w|\d])+/";
    $string = "[abc - 123 - def - 456 - ghi - 789 - jkl]";
    preg_match_all($pattern, $string, $matches);
    print_r($matches[0]);
?>
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => abc
    [1] => 123
    [2] => def
    [3] => 456
    [4] => ghi
    [5] => 789
    [6] => jkl
)
Run Code Online (Sandbox Code Playgroud)

  • @carlosdubusm:您应该编辑您的问题以包含您要匹配的**实际**字符串.否则,你得到的答案可能不适合你.:) (2认同)

Tho*_*ner 6

SPL preg_match_all将从$matches变量的索引1开始返回正则表达式组.例如,如果您只想获得第二组,则可以使用$matches[2].

句法:

$matches = array(); 
preg_match_all(\
    '/(He)\w+ (\w+)/', 
    "Hello world\n Hello Sunshine", 
    $matches
); 
var_dump($matches);
Run Code Online (Sandbox Code Playgroud)

结果:

array(3) {
  [0] =>
  array(2) {
    [0] =>
    string(11) "Hello world"
    [1] =>
    string(14) "Hello Sunshine"
  }
  [1] =>
  array(2) {
    [0] =>
    string(2) "He"
    [1] =>
    string(2) "He"
  }
  [2] =>
  array(2) {
    [0] =>
    string(5) "world"
    [1] =>
    string(8) "Sunshine"
  }
}
Run Code Online (Sandbox Code Playgroud)

PS这个答案是在谷歌搜索引导后发布的问题标题的上下文.这是我在搜索此主题时感兴趣的信息.


And*_*rew 6

要将匹配项分组,请使用括号。例如:

$string = 'bob';
preg_match('/bob/', $string, $matches);
Run Code Online (Sandbox Code Playgroud)

$matches['bob']

preg_match('/(b)(o)(b)/', $string, $matches);
Run Code Online (Sandbox Code Playgroud)

$matches['bob','b','o','b']