2013-02-05 25 views
0

可能重复:
How to add http:// if it’s not exists in the URL?如何使用preg_match更改URL的方案?

说我想匹配,可能有两种http://https://或既不是它的URL。当我替换它时,如果它在前面,我想在前面有https://,但是如果它是http://或者什么也没有,我想在开始时有http://

我无法弄清楚如何用preg_match表达式或非PHP倾斜的,搜索和替换PHP函数。

+0

[你有什么尝试?](http://www.whathaveyoutried.com/)请参阅[问问建议](http://stackoverflow.com/questions/ask-advice)。 –

+0

阅读http://www.regular-expressions.info/conditional.html可能会持有你的答案。 – Jerry

回答

0

像这样的东西应该工作,如果你想要一个正则表达式的解决方案。

preg_replace('|^(?:http(s)?://)?(.+)$|', 'http\\1://\\2', $url);

虽然我可能会使用parse_url,并把它重新走到一起。

+0

我的问题在于没有任何http://或https:// –

+1

之类的URL,例如'www.stackoveflow.com'你甚至尝试过吗? 'echo preg_replace('| ^(?:http(s)?://)?(。+)$ |','http \\ 1:// \\ 2','www.stackoverflow.com'); ' – Rob