iT邦幫忙

0

php preg_match_all 抓取介於兩個tags中間的資料

匿名 2015-11-30 17:59:263258 瀏覽

Hi!各位大大好

小弟的問題是我用下面的程式碼

preg_match_all("/<h1>(.*?)<\/h1>/",$html,$matches);

試著抓下面的資料,我只需要<h1>aa</h1>和<h1>cc</h1>這兩筆但都會把<h1>bb</h1>跟<h1>dd</h1>給一起抓出來,想麻煩各位先進指點指點~“~

&lt;span class="apple">
    &lt;h1>aa&lt;/h1>&lt;strong>abc&lt;/strong>
&lt;/span>
&lt;span class="apple banana">
    &lt;h1>bb&lt;/h1>&lt;strong>def&lt;/strong>
&lt;/span>
&lt;span class="apple">
    &lt;h1>cc&lt;/h1>&lt;strong>abc&lt;/strong>
&lt;/span>
&lt;span class="apple banana">
    &lt;h1>dd&lt;/h1>&lt;strong>def&lt;/strong>
&lt;/span>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
wiseguy
iT邦超人 1 級 ‧ 2015-12-01 10:42:39
最佳解答

你要的 aa, cc 是以 class="apple" 為分別吧?若是如此,那就改為這樣即可:

&lt;pre class="c" name="code">preg_match_all('/apple">\s*&lt;h1>(.*?)&lt;\/h1>/',$html,$matches);
匿名 檢舉

wise大!!太感謝了 這麼做確實就可以搞定了!!謝謝

想再請教您這段code要怎麼解讀比較好...小弟對正則真的不行

&lt;pre class="c" name="code">/apple">\s*&lt;h1>(.*?)&lt;\/h1>

最後想請問wise大有建議的搜尋方向或是文件可以讓我做學習正則的參考嗎 感謝您 筆記

wiseguy iT邦超人 1 級 ‧ 2015-12-01 20:40:44 檢舉

怎麼解讀?不就是把前面的 class="apple"> 再補上去就好了嗎?讓這個 RegExp 有差異性,能抓出你要的部份就行了,所以我只從 apple開始抓。
學習 RegExp 就是多寫+多看別人怎麼寫。

我要發表回答

立即登入回答