php 正则抓取页面内容_php 正则表达式 抓取网页内容

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

1.

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

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');

//取得所有img標籤,並儲存至二維陣列match

preg_match_all('#]*>#i',

$text, $match);

//印出match

print_r($match);

?>

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');

//取得所有img標籤,並儲存至二維陣列match

preg_match_all('#]*>#i', $text, $match);

//印出match

print_r($match);

?>

2.

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

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');

//取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)

preg_match('/]*>/Ui',

$text, $match);

//印出match

print_r($match);

?>

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/');

//取得第一個img標籤,並儲存至陣列match(regex語法與上述同義)

preg_match('/]*>/Ui', $text, $match);

//印出match

print_r($match);

?>

3.

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

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');

//去除換行及空白字元(序列化內容才需使用)

//$text=str_replace(array("\r","\n","\t","\s"), '',

$text);

//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/

]*id="PostContent"[^>]*>(.*?)

/si',$text,$match);

//印出match[0]

print($match[0]);

?>

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');

//去除換行及空白字元(序列化內容才需使用)

//$text=str_replace(array("\r","\n","\t","\s"), '', $text);

//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/

]*id="PostContent"[^>]*>(.*?) /si',$text,$match);

//印出match[0]

print($match[0]);

?>

4.

上述2及3的結合:測試

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');

//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/

]*id="PostContent"[^>]*>(.*?)

/si',$text,$match);

//取得第一個img標籤,並儲存至陣列match2

preg_match('/]*>/Ui',

$match[0], $match2);

//印出match2[0]

print_r($match2[0]);

?>

//取得指定位址的內容,並儲存至text

$text=file_get_contents('http://andy.diimii.com/2009/01/seo化的關鍵字廣告連結/');

//取出div標籤且id為PostContent的內容,並儲存至陣列match

preg_match('/

]*id="PostContent"[^>]*>(.*?) /si',$text,$match);

//取得第一個img標籤,並儲存至陣列match2

preg_match('/]*>/Ui', $match[0], $match2);

//印出match2[0]

print_r($match2[0]);

?>

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

Details | PCRE Functions | Introduction to PHP

Regex)

From[http://xiaoniba.net/html/jiaocheng/PHPjiaocheng/2009/0428/464.html]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值