简体   繁体   English

html标签之间的PHP preg_match图像

[英]PHP preg_match image between html tags

I've got an html template like this: 我有一个像这样的html模板:

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

And i want to extract "DESIRED IMAGE LINK" inside the "" tag, currently i'm using this: 我想在“”标签中提取“DESIRED IMAGE LINK”,目前我正在使用它:

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

But it doesn't work, the error is: 但它不起作用,错误是:

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

How can i fix it? 我该如何解决? Thanks 谢谢

The answer is, don't use regular expressions. 答案是,不要使用正则表达式。

$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;
}

See also: DOMDocument DOMXPath 另请参见: DOMDocument DOMXPath

如果你打算解析html尝试使用带有xpath的 DOM

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

你错过了领先的分隔符/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM