正则表达式从锚标记中提取Url

时间:2009-06-08 16:57:35

标签: regex

我想从锚标签中提取http链接?应提取的扩展名应仅为WMV文件。

3 个答案:

答案 0 :(得分:2)

因为HTML的语法规则太松散,所以任何可靠性都很难(除非你绝对肯定知道你的所有标签都会在其属性值周围使用双引号)。以下是一些相当普遍的基于正则表达式的代码:

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

答案 1 :(得分:1)

我不会用正则表达式做这个 - 我可能会使用jQuery:

jQuery('a[href$=.wmv]').attr('href')

将此与chaos的简化正则表达式示例进行比较,该示例(如上所述)不处理繁琐/复杂的标记,并且您希望理解为什么DOM解析器比这类问题的正则表达式更好。

答案 2 :(得分:1)

正则表达式:

<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a>

[注意:\ s *用于多个地方,以匹配html中可能出现的额外空白字符。]

示例C#代码:

/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// Matches only for .wmv files
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetailsWMV(string htmlATag, out string wmvLink, out string name)
{
    wmvLink = null;
    name = null;

    string pattern = "<a\\s*href\\s*=\\s*(?:(\"|\')(?<link>[^\"]*.wmv)(\"|\'))\\s*>(?<name>.*)\\s*</a>";

    if (Regex.IsMatch(htmlATag, pattern))
    {
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        wmvLink = r.Match(htmlATag).Result("${link}");
        name = r.Match(htmlATag).Result("${name}");
        return true;
    }
    else
        return false;
}

MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file'>Name of File</a></td>", 
                out wmvLink, out name); // No match
MyRegEx.TryGetHrefDetailsWMV("<td><a href='/path/to/file.wmv'>Name of File</a></td>",
                out wmvLink, out name); // Match
MyRegEx.TryGetHrefDetailsWMV("<td><a    href='/path/to/file.wmv'   >Name of File</a></td>", out wmvLink, out name); // Match
相关问题