【问题标题】:PHP Regular expression: Get all urls with question markPHP正则表达式:获取所有带问号的网址
【发布时间】:2013-06-15 05:35:11
【问题描述】:

我有这个正则表达式:

preg_match_all("/<a\s.*?href\s*=\s*['|\"](.*?)(?=#|\"|')/si", $data, $matches);

要查找所有网址,它可以正常工作,但是如何修改它以仅查找带有问号的网址?

例子:

<a href="http://site.com/index.php">0</a><a href="http://site.com/index.php?id=1">1</a><a href="http://site.com/calc/index.php?id=1&scheme=Venus">2</a><a href="http://site.com/catalogue/data.php">3</a>

preg_match_all 将返回:

http://site.com/index.php?id=1

http://site.com/calc/index.php?id=1&scheme=Venus

【问题讨论】:

    标签: php regex html-parsing


    【解决方案1】:
    preg_match_all("@<a\s*href\s*=[\'\"]([^\'\"]+\?[^\'\"]+)[\'\"]@si", $data, $matches);
    

    试试这个。

    【讨论】:

      【解决方案2】:

      不要试图让所有事情都发生在一个正则表达式中。使用你现有的方法,然后单独检查你返回的 URL 是否有问号。

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

      【讨论】:

      • 谢谢,我去查一下。
      【解决方案3】:

      安迪·莱斯特给了你正确的答案。

      这是你的正则表达式:

      <a\s.*?href\s*=\s*['|\"](.*?\?.*?)(?=#|\"|')
      

      如下所示:

      http://rubular.com/r/LHi11VMMR9

      【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 2017-11-24
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多