【问题标题】:Regular Expression to Extract the Url out of the Anchor Tag从锚标记中提取 URL 的正则表达式
【发布时间】:2009-06-08 16:57:34
【问题描述】:

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

【问题讨论】:

标签: regex


【解决方案1】:

因为 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;
}

【讨论】:

    【解决方案2】:

    正则表达式:

    <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
    

    【讨论】:

      【解决方案3】:

      我不会用正则表达式来做这件事——我可能会使用 jQuery:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-12
        • 1970-01-01
        • 1970-01-01
        • 2014-04-22
        相关资源
        最近更新 更多