且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

preg_match_all成简单的数组

更新时间:2022-06-05 17:51:16

您总是会得到一个多维数组回来了,不过,你可以得到接近你想要这样的:

You will always get a multidimensional array back, however, you can get close to what you want like this:

if (preg_match_all('#<h2>(.*?)</h2>#is', $source, $output, PREG_PATTERN_ORDER))
    $matches = $output[0]; // reduce the multi-dimensional array to the array of full matches only

如果你不希望子匹配的话,那么使用非捕获分组:

And if you don't want the submatch at all, then use a non-capturing grouping:

if (preg_match_all('#<h2>(?:.*?)</h2>#is', $source, $output, PREG_PATTERN_ORDER))
    $matches = $output[0]; // reduce the multi-dimensional array to the array of full matches only

请注意,这个调用preg_match_all使用preG_PATTERN_ORDER代替preG_SET_ORDER:

Note that this call to preg_match_all is using PREG_PATTERN_ORDER instead of PREG_SET_ORDER:

preG_PATTERN_ORDER结果排序使得$ matches [0]是一个数组
  全模式匹配,$匹配[1]是匹配的字符串数组
  第一个括号中的子模式,等等。

PREG_PATTERN_ORDER Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

preG_SET_ORDER结果排序使得$ matches [0]是第一个数组
  比赛集,$匹配[1]为第二组匹配的数组,
  等等。

PREG_SET_ORDER Orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on.

请参阅:http://php.net/manual/en/function.$p$pg-match-all.php