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

时间:2010-08-19 05:30:21

标签: php regex deduplication

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

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

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

将所有图片网址收集到一个数组中,然后使用array_unique()删除重复项。

$my_image_links = array_unique( $my_image_links );
// No more duplicates

如果您真的想要使用正则表达式,那么我们可以假设每个图像名称都被'"或空格,制表符或换行符或者开头包围行,><以及您能想到的任何其他内容。那么,我们就可以做到:

$pattern = '/[\'" >\t^]([^\'" \n\r\t]+\.(jpe?g|bmp|gif|png))[\'" <\n\r\t]/i';
preg_match_all($pattern, html_entity_decode($resultFromCurl), $matches);
$imgs = array_unique($matches[1]);

以上内容将捕获图像链接,例如:

<p>Hai guys look at this ==> http://blah.com/lolcats.JPEG</p>

Live example