我有一个像这样的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 '.'
我该如何解决?感谢
答案 0 :(得分: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;
}
另请参阅:DOMDocument DOMXPath
答案 1 :(得分:1)
答案 2 :(得分:0)
$pattern = '/<div class="cont">.*?src=["\']?([^"\']?.*?(png|jpg|jpeg|gif))["\']?/i
您错过了前导分隔符/
。