PHP RegEx won't pick up question mark

百般思念 提交于 2019-12-11 08:16:21

问题


I am trying to match urls in a string using the PHP function "preg_match_all". It works fine, except it will not match urls with question marks in them.

For example, this will match fine:

http://espn.com/mlb

But this will not match:

http://espn.com/mlb?player=71

Here is the regex I am using,

$regexUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

I cannot figure out why the question mark is not being picked up by the \S. I've tried a lot of different expressions and cannot get the question mark to match. Any ideas?

EDIT:

It turns out preg_match_all was returning true, but I was not escaping the question mark in the preg_match_all output, so the preg_replace call that I was making later on was failing.


回答1:


The question mark means that the preceding match is optional, i.e.

/https?/

will cause both "http" and "https" to match. You must escape the question mark to match it.

For example:

/https\?/

will now only match "https?".



来源:https://stackoverflow.com/questions/10116505/php-regex-wont-pick-up-question-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!