PHP 正则表达式组捕获

2022-08-30 21:51:18

我有以下正则表达式:

\[([^ -\]]+)( - ([^ -\]]+))+\]

这已成功匹配以下内容:

[abc - def - ghi - jkl]

但匹配是:

Array
(
    [0] => [abc - def - ghi - jkl]
    [1] => abc
    [2] =>  - jkl
    [3] => jkl
)

我需要的是这样的东西:

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

我能够在C#中查看组“捕获”来执行此操作。如何在PHP中执行此操作?


答案 1

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

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

答案 2

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

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

输出:

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

推荐