我有preg_match_all函数:
preg_match_all('#<h2>(.*?)</h2>#is', $source, $output, PREG_SET_ORDER);
它正在按预期工作,但问题是,它preg_matches所有项目两次,并进入一个巨大的多维数组,例如,如预期的那样,preg_matched所有11项需要,但两次,并进入一个多维数组:< / p>
Array
(
[0] => Array
(
[0] => <h2>10. <em>Cruel</em> by St. Vincent</h2>
[1] => 10. <em>Cruel</em> by St. Vincent
)
[1] => Array
(
[0] => <h2>9. <em>Robot Rock</em> by Daft Punk</h2>
[1] => 9. <em>Robot Rock</em> by Daft Punk
)
[2] => Array
(
[0] => <h2>8. <em>Seven Nation Army</em> by the White Stripes</h2>
[1] => 8. <em>Seven Nation Army</em> by the White Stripes
)
[3] => Array
(
[0] => <h2>7. <em>Do You Want To</em> by Franz Ferdinand</h2>
[1] => 7. <em>Do You Want To</em> by Franz Ferdinand
)
[4] => Array
(
[0] => <h2>6. <em>Teenage Dream</em> by Katie Perry</h2>
[1] => 6. <em>Teenage Dream</em> by Katie Perry
)
[5] => Array
(
[0] => <h2>5. <em>Crazy</em> by Gnarls Barkley</h2>
[1] => 5. <em>Crazy</em> by Gnarls Barkley
)
[6] => Array
(
[0] => <h2>4. <em>Kids</em> by MGMT</h2>
[1] => 4. <em>Kids</em> by MGMT
)
[7] => Array
(
[0] => <h2>3. <em>Bad Romance</em> by Lady Gaga</h2>
[1] => 3. <em>Bad Romance</em> by Lady Gaga
)
[8] => Array
(
[0] => <h2>2. <em>Pumped Up Kicks</em> by Foster the People</h2>
[1] => 2. <em>Pumped Up Kicks</em> by Foster the People
)
[9] => Array
(
[0] => <h2>1. <em>Paradise</em> by Coldplay</h2>
[1] => 1. <em>Paradise</em> by Coldplay
)
[10] => Array
(
[0] => <h2>Song That Get Stuck In Your Head YouTube Playlist</h2>
[1] => Song That Get Stuck In Your Head YouTube Playlist
)
)
如何将此数组转换为简单数组并且没有这些重复项?非常感谢你。
答案 0 :(得分:6)
你将永远得到一个多维数组,但是,你可以接近你想要的东西:
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
如果你根本不想要子匹配,那么使用非捕获分组:
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:
PREG_PATTERN_ORDER对结果进行排序,以便$ matches [0]是一个数组 完整模式匹配,$ matches [1]是一个匹配的字符串数组 第一个带括号的子模式,依此类推。
PREG_SET_ORDER对结果进行排序,以便$ matches [0]是第一个数组 匹配集,$ matches [1]是第二组匹配的数组,和 等等。
答案 1 :(得分:1)
使用
#<h2>(?:.*?)</h2>#is
作为你的正则表达式。如果您使用非捕获组(?:
表示的话),则反向引用将不会显示在数组中。