its*_*ood 1 php regex preg-match-all
我正在尝试使用 PHP 函数“preg_match_all”来匹配字符串中的 url。它工作正常,但它不会匹配带有问号的网址。
例如,这将很好地匹配:
http://espn.com/mlb
Run Code Online (Sandbox Code Playgroud)
但这不会匹配:
http://espn.com/mlb?player=71
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的正则表达式,
$regexUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
Run Code Online (Sandbox Code Playgroud)
我不明白为什么问号没有被 \S 选中。我尝试了很多不同的表达方式,但无法让问号匹配。有任何想法吗?
编辑:
事实证明 preg_match_all 返回 true,但我没有转义 preg_match_all 输出中的问号,因此我稍后进行的 preg_replace 调用失败了。
问号表示前面的匹配是可选的,即
/https?/
Run Code Online (Sandbox Code Playgroud)
将导致“http”和“https”匹配。您必须转义问号才能匹配它。
例如:
/https\?/
Run Code Online (Sandbox Code Playgroud)
现在仅匹配“https?”。