使用正则表达式正确解析网址

时间:2018-04-19 06:46:32

标签: php regex

我有来自Wordpress的这个正则表达式。但是我无法正确地调整它来解析URL。我只想解析http/https/ftp个链接。

我尝试更改方案部分:(http|https|ftp)+://,但它无效。

对于网址:testhttp://google.com

匹配应为:http://google.com

当前比赛:testhttp://google.com

谢谢!

~
    ([\\s(<.,;:!?])                                        # 1: Leading whitespace, or punctuation
    (                                                      # 2: URL
        [\\w]{1,20}+://                                # Scheme and hier-part prefix
        (?=\S{1,2000}\s)                               # Limit to URLs less than about 2000 characters long
        [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+         # Non-punctuation URL character
        (?:                                            # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
            ['.,;:!?)]                            # Punctuation URL character
            [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
        )*
    )
    (\)?)                                                  # 3: Trailing closing parenthesis (for parethesis balancing post processing)
~xS

1 个答案:

答案 0 :(得分:0)

好的,我认为这里的问题是你的正则表达式假设网址前面有第一行注释中提到的空格或标点符号。如果你希望正则表达式匹配文本中的url而没有任何分离,我会删除第一行并按照你的尝试更改方案部分,但是在非捕获组(?:https?|ftp)://中没有+ Quantifier。