preg_match_all into simple array

纵然是瞬间 提交于 2019-12-04 05:09:48

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

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

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 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.

See: http://php.net/manual/en/function.preg-match-all.php

Use

#<h2>(?:.*?)</h2>#is 

as your regex. If you use a non capturing group (which is what ?: signifies), a backreference won't show up in the array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!