【问题标题】:Regex - Find the match that is inside a match正则表达式 - 查找匹配项中的匹配项
【发布时间】:2013-09-10 16:49:15
【问题描述】:

如果字符串是

<li>Your browser may be missing a required plug-in contained in <a href="http://get.adobe.com/reader/">Adobe Acrobat Reader</a>.  Please reload this page after installing the missing component.<br />If this error persists, you can also save a copy of <a href="test.pdf">

我写的正则表达式是

/href=.*?.pdf/

这会导致捕获第一个“href”并以“.pdf”结尾。我需要它从第二个 href 开始。换句话说,它应该只捕获以 .pdf 结尾的 href

我应该如何使用正则表达式来解决这个问题?

【问题讨论】:

  • 不要使用正则表达式解析 HTML。使用适当的 HTML 解析模块。 您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。请参阅htmlparsing.com/phpthis SO thread,了解如何使用已经编写、测试和调试过的 PHP 模块正确解析 HTML。

标签: php regex html-parsing


【解决方案1】:

你可以试试这个正则表达式:

/href=[^>]+\.pdf/

regex101 demo

大多数时候,当你可以避免 .*.+(或它们的惰性版本)时,它会更好:)

另外,不要忘记转义句号。

【讨论】:

    【解决方案2】:

    您应该使用 DOM 而不是使用正则表达式来解析 HTML 或 XML。在 PHP 中有 DOMDocument 类:

    $doc = new DOMDocument();
    $doc->loadHTML('<li>Your browser may be missing a required plug-in contained in <a href="http://get.adobe.com/reader/">Adobe Acrobat Reader</a>.  Please reload this page after installing the missing component.<br />If this error persists, you can also save a copy of <a href="http://www.police.vt.edu/VTPD_v2.1/crime_stats/crime_logs/data/VT_2011-01_Crime_Log.pdf">');
    
    $links = $doc->getElementsByTagName('a');
    foreach($links as $link) {
        echo $link->getAttribute('href');
    }
    

    【讨论】:

    • 问题是有时我需要从 Javascript 中获取链接。 (即 document.location.href...)
    • javascript 也有 dom 方法
    • 在浏览器中,更简单:只需依赖document.links
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2015-12-26
    • 2015-06-01
    • 2013-12-01
    相关资源
    最近更新 更多