[英]PHP preg_match image between html tags
我有一個像這樣的html模板:
<div class="cont">
<div class="...">
<p>...<p>
<img alt="" class="popup" src="DESIRED IMAGE LINK" style="..." /></p><p>...</p>
....
我想在“”標簽中提取“DESIRED IMAGE 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 '.'
我該如何解決? 謝謝
答案是,不要使用正則表達式。
$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;
}
另請參見: DOMDocument DOMXPath
$pattern = '/<div class="cont">.*?src=["\\']?([^"\\']?.*?(png|jpg|jpeg|gif))["\\']?/i
你錯過了領先的分隔符/
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.