Preg_match_all也返回初始值

时间:2017-04-11 18:01:57

标签: php arrays preg-match-all

如果我制作正则表达式并将数组$content传递给它:

preg_match_all(/([0-9]+)\/([0-9]+)/, $content, $matches);

$content是数组:

Name Address 77/88 Country
Name Address 71/90 Country
Name Address 72/43 Country
Name Address 76/55 Country
Name Country
Name Address

它将返回$matches

  array(4) {
    [0]=>
    string(5) "77/88"
    [1]=>
    string(5) "71/90"
    [2]=>
    string(5) "72/43"
    [3]=>
    string(5) "76/55"
  }

但是我能以某种方式得到匹配值的初始数组$content值吗?

1 个答案:

答案 0 :(得分:0)

$content需要是preg_match_all()的字符串:

preg_match_all('/^.*?([0-9]+)\/([0-9]+).*$/m', $content, $matches);

收率:

Array
(
    [0] => Array
        (
            [0] => Name Address 77/88 Country
            [1] => Name Address 71/90 Country
            [2] => Name Address 72/43 Country
            [3] => Name Address 76/55 Country
        )

    [1] => Array
        (
            [0] => 77
            [1] => 71
            [2] => 72
            [3] => 76
        )

    [2] => Array
        (
            [0] => 88
            [1] => 90
            [2] => 43
            [3] => 55
        )
)

如果$content确实是一个数组:

$matches = preg_grep('/([0-9]+)\/([0-9]+)/', $content);

收率:

Array
(
    [0] => Name Address 77/88 Country
    [1] => Name Address 71/90 Country
    [2] => Name Address 72/43 Country
    [3] => Name Address 76/55 Country
)