Regex - PHP 字串中匹配url

來源:互聯網
上載者:User
需求:

用戶端傳過來一段字串,需要從字串中匹配出所有的url,包括網域名稱或IP後面的參數(含連接埠)

URL範例:

http://127.0.0.1/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23或者http://www.baidu.com/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23

當然簡單URL也是要匹配出來的
求解正則

回複內容:

需求:

用戶端傳過來一段字串,需要從字串中匹配出所有的url,包括網域名稱或IP後面的參數(含連接埠)

URL範例:

http://127.0.0.1/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23或者http://www.baidu.com/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23

當然簡單URL也是要匹配出來的
求解正則

先用比較寬泛的正則匹配出所有的url,例如

https?:\/\/\S+

然後對於這堆url依次採用parse_url函數

^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$http://regexlib.com/Search.aspx?k=url&c=-1&m=5&ps=20

Java 大概這麼寫

String str = "接收到的字串"String regex = "(http:|https:)//[^[A-Za-z0-9,:\\._\\?%&+\\-=/#]]*";        Pattern pattern = Pattern.compile(regex);        Matcher matcher = pattern.matcher(str);        while (matcher.find()) {            String url=matcher.group();            System.out.println(url);        }

以下字串通過測試.

String str="http://127.0.0.1:6666/ " +                "https://www.baidu.com/ " +                "http://127.0.0.1/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23\n" +                "或者\n" +                "哈哈http://www.baidu.com:85676/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23 6666都是對的";

輸出

http://127.0.0.1:6666/https://www.baidu.com/http://127.0.0.1/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23http://www.baidu.com:85676/metinfo/img/img.php?class1=1&serch_sql=%201=if%28ascii%28substr%28user%28%29,1,1%29%29=114,1,2%29%23

什麼,你問的式PHP?抱歉,我不會PHP。。。
正則一樣的,自己動動腦袋吧。

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.