gpt4 book ai didi

php - preg_match_all 到简单数组

转载 作者:可可西里 更新时间:2023-11-01 12:53:30 26 4
gpt4 key购买 nike

我有 preg_match_all 函数:

preg_match_all('#<h2>(.*?)</h2>#is', $source, $output, PREG_SET_ORDER);

它按预期工作,但问题是,它 preg_matches 所有项目两次并进入一个巨大的多维数组,例如,它按预期预匹配所需的所有 11 个项目,但两次并进入一个多维数组:

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
)

)

如何将这个数组转换成简单的数组并且没有那些重复的项目?非常感谢。

最佳答案

你总是会得到一个多维数组,但是,你可以像这样接近你想要的:

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

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

关于php - preg_match_all 到简单数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com