2012-11-14 75 views
7

我有preg_match_all功能:preg_match_all成簡單陣列

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

它的工作如預期,但問題是,它preg_matches所有項目兩次,變成了一個巨大的多維數組像這樣的例子在那裏,如預期,preg_matched所有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 
     ) 

) 

如何這個數組轉換成簡單的,沒有那些重複的項目?非常感謝你。

回答

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]是第一組 組匹配的數組,匹配[1]是第二組匹配的數組,以及 等。

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

+1

這大概應該是$匹配= $輸出[0]。謝謝它工作:) – DadaB

+0

@MantasBalaisa哦,你是對的!我不確定我在想什麼。謝謝。固定。 – jimp

+0

可能需要避開正斜槓? – Dan

1

使用

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

爲您的正則表達式。如果您使用非捕獲組(這是?:表示的內容),反向引用將不會顯示在數組中。