[英]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.