Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

regex - Regular Expression to Extract the Url out of the Anchor Tag

I want to extract the http link from inside the anchor tags? The extension that should be extracted should be WMV files only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because HTML's syntactic rules are so loose, it's pretty difficult to do with any reliability (unless, say, you know for absolute certain that all your tags will use double quotes around their attribute values). Here's some fairly general regex-based code for the purpose:

function extract_urls($html) {
    $html = preg_replace('<!--.*?-->', '', $html);
    preg_match_all('/<as+[^>]*href="([^"]+)"[^>]*>/is', $html, $matches);
    foreach($matches[1] as $url) {
        $url = str_replace('&amp;', '&', trim($url));
        if(preg_match('/.wmv/i', $url) && !in_array($url, $urls))
            $urls[] = $url;
    }
    preg_match_all('/<as+[^>]*href='([^']+)'[^>]*>/is', $html, $matches);
    foreach($matches[1] as $url) {
        $url = str_replace('&amp;', '&', trim($url));
        if(preg_match('/.wmv/i', $url) && !in_array($url, $urls))
            $urls[] = $url;
    }
    preg_match_all('/<as+[^>]*href=([^"'][^> ]*)[^>]*>/is', $html, $matches);
    foreach($matches[1] as $url) {
        $url = str_replace('&amp;', '&', trim($url));
        if(preg_match('/.wmv/i', $url) && !in_array($url, $urls))
            $urls[] = $url;
    }
    return $urls;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...