当前位置: 主页 > 教程 > PHP教程 >

php抓取特定标签内容/正则表达式

编辑:admin 日间:2009-04-28 02:11

昨天有個朋友在問我說,php怎麼抓取網頁某個div區塊的內容。像funp推推王那樣每次推文都會顯示文章內的圖片,提供縮圖撰擇,又是怎麼做到的?其實這語法出乎意料的簡短…
php抓取網頁特定div區塊及圖片

1. 取得指定網頁內的所有圖片測試

  1. <?php   
  2. //取得指定位址的內容,並儲存至text   
  3. $text=file_get_contents('http://andy.diimii.com/');    
  4.   
  5. //取得所有img標籤,並儲存至二維陣列match   
  6. preg_match_all('#<img[^>]*>#i'$text$match);   
  7.   
  8. //印出match   
  9. print_r($match);   
  10. ?>  

2. 取得指定網頁內的第一張圖片測試

  1. <?php   
  2. //取得指定位址的內容,並儲存至text   
  3. $text=file_get_contents('http://andy.diimii.com/');   
  4.   
  5. //取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)   
  6. preg_match('/<img[^>]*>/Ui'$text$match);   
  7.   
  8. //印出match   
  9. print_r($match);   
  10. ?>  

3. 取得指定網頁內的特定div區塊(藉由id判斷)測試

  1. <?php   
  2. //取得指定位址的內容,並儲存至text   
  3. $text=file_get_contents('http://andy.diimii.com/2009/01/seo%e5%8c%96%e7%9a%84%e9%97%9c%e9%8d%b5%e5%ad%97%e5%bb%a3%e5%91%8a%e9%80%a3%e7%b5%90/');    
  4.   
  5. //去除換行及空白字元(序列化內容才需使用)   
  6. //$text=str_replace(array("\r","\n","\t","\s"), '', $text);      
  7.   
  8. //取出div標籤且id為PostContent的內容,並儲存至陣列match   
  9. preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match);   
  10.   
  11. //印出match[0]   
  12. print($match[0]);   
  13. ?>  

4. 上述2及3的結合測試

  1. <?php   
  2. //取得指定位址的內容,並儲存至text   
  3. $text=file_get_contents('http://andy.diimii.com/2009/01/seo%e5%8c%96%e7%9a%84%e9%97%9c%e9%8d%b5%e5%ad%97%e5%bb%a3%e5%91%8a%e9%80%a3%e7%b5%90/');       
  4.   
  5. //取出div標籤且id為PostContent的內容,並儲存至陣列match   
  6. preg_match('/<div[^>]*id="PostContent"[^>]*>(.*?) <\/div>/si',$text,$match);      
  7.   
  8. //取得第一個img標籤,並儲存至陣列match2   
  9. preg_match('/<img[^>]*>/Ui'$match[0], $match2);    
  10.   
  11. //印出match2[0]   
  12. print_r($match2[0]);   
  13. ?>  

後記:用正規表達式Regex來做真的很方便,但老實說我規則常會忘掉,記錄一下幾篇文章好了(Regular Expression Details | PCRE Functions | Introduction to PHP Regex