2013-02-05 22 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