2013-08-26 68 views
0

如何檢測文本中是否存在某些圖片html標記並提取圖片的網址?從文本和html標記中檢測並提取圖片url

例如,

提取此網址:

http:// 
www.someurl.com/somefileprocessor.php/12345/somedir/somesubdir/someniceimage.j 
pg 

從這個標記(此標記可以是文本和/或HTML的另一束內)

<img title="Some nice title" border="0" 
hspace="0" alt="some useful hint" src="http:// 
www.someurl.com/somefileprocessor.php/12345/somedir/somesubdir/someniceimage.j 
pg" width="629" height="464" /> 

感謝的提前 安傑洛

+0

好像答案就在這裏:http://stackoverflow.com/questions/2143202/any-preg-match-to-extract-image -urls,從文本。 – bredikhin

回答

2

一快速嘗試<img/>標記特定的正則表達式:

preg_match_all('/<img[^>]*?\s+src\s*=\s*"([^"]+)"[^>]*?>/i', $str, $matches); 

Example

+0

img和src屬性之間至少應該有一個空格。你應該添加一個\ s +。這失敗了: Frizi

+0

@Frizi你是對的,很好的發現 - 更新。 – Emissary

0

您可以使用CRUL獲取內容,然後從內容中提取所有img標籤。 通過curl獲取數據:

function get_data($url) { 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

然後使用正則表達式來提取數據。

^https?://(?:[a-z\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$ 

這可以幫助你提取所有的圖像URL(在img標籤或不)。

如果需要爬行,你可以使用PHPCrawl

0

感謝的很多的awnswers,因爲我瞭解一些更多的PHP。我嘗試這個快速和骯髒的方式,還提取了圖像的URL

$imageurl = strstr($title, 'src',FALSE); 
$imageurl = strstr($imageurl,'"',FALSE); 
$imageurlpos = strpos($imageurl,'"'); 
$imageurl = substr($imageurl,$imageurlpos+1); 
$imageurlpos = strpos($imageurl,'"'); 
$imageurl = substr($imageurl,0,$imageurlpos);