2012-12-18 152 views
1

我有一個HTML模板是這樣的:PHP的preg_match圖像

<div class="cont"> 
    <div class="..."> 
    <p>...<p> 
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p> 
    .... 

,我想提取「所需的圖像LINK」的「」標籤內,我目前使用這樣的:

$pattern = '<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i'; 
if (preg_match($pattern, $content, $image)) 
    ..... 

但它不工作,錯誤的是:

warning: preg_match() [function.preg-match]: Unknown modifier '.' 

我怎樣才能解決這個問題?由於

回答

3

答案是,不要使用正則表達式。

$contents = <<<EOS 
<div class="cont"> 
    <div class="..."> 
    <p>...<p> 
    <img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p> 
EOS; 

$doc = new DOMDocument; 
libxml_use_internal_errors(true); 
$doc->loadHTML($contents); 
libxml_clear_errors(); 

$xp = new DOMXPath($doc); 

// get first image inside div.cont 
foreach($xp->query('//div[@class="cont"]//img[1]') as $node) { 
     // output the src attribute 
     echo $node->getAttribute('src'), PHP_EOL; 
} 

參見:DOMDocumentDOMXPath

+0

完美的作品!謝謝 – Alvins

0

$pattern = '/<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i

你錯過了你的領導分隔符/

+0

它不工作 – Alvins

1

如果你打算解析HTML嘗試使用DOMxpath

+0

DOM是不總是X(HT)ML有效。我強烈建議不要這樣做。對於簡單的東西,正則表達式工作正常。 – Halcyon