从HTML中抓取唯一的图片网址

1 php regex deduplication

使用PHP来卷曲网页(用户输入的一些URL,我们假设它是有效的).示例:http://www.youtube.com/watch?v = Hovbx6rvBaA

我需要解析HTML并提取看起来像图像的所有重复数据删除的URL.不只是在该页面上的那些,img src=""但以jpe?g|bmp|gif|png该页面上的任何URL结尾等.(换句话说,我不想解析DOM但想要使用RegEx).

我计划然后卷曲URL的宽度和高度信息,并确保它们确实是图像,所以不要担心与安全相关的东西.

Sha*_*obe 5

使用DOM有什么问题?它可以让您更好地控制信息的上下文,并且您提取的内容实际上是URL的可能性要高得多.

<?php
$resultFromCurl = '
    <html>
    <body>
    <img src="hello.jpg" />
    <a href="yep.jpg">Yep</a>
    <table background="yep.jpg">
    </table>
    <p>
        Perhaps you should check out foo.jpg! I promise it 
        is safe for work.
    </p>
    </body>
    </html>
';

// these are all the attributes i could think of that
// can contain URLs.
$queries = array(
    '//table/@background',
    '//img/@src',
    '//input/@src',
    '//a/@href',
    '//area/@href',
    '//img/@longdesc',
);

$dom = @DOMDocument::loadHtml($resultFromCurl);
$xpath = new DOMXPath($dom);

$urls = array();
foreach ($queries as $query) {
    foreach ($xpath->query($query) as $link) {
        if (preg_match('@\.(gif|jpe?g|png)$@', $link->textContent))
            $urls[$link->textContent] = true;
    }
}

if (preg_match_all('@\b[^\s]+\.(?:gif|jpe?g|png)\b@', $dom->textContent, $matches)) {
    foreach ($matches as $m) {
        $urls[$m[0]] = true;
    }
}

$urls = array_keys($urls);
var_dump($urls);
Run Code Online (Sandbox Code Playgroud)