0

Possible Duplicate:
How to add http:// if it’s not exists in the URL?

Say I want to match a URL that may have either http://, https:// or neither in it. When I replace it, I want to have https:// at the front if it was there, but if it was http:// or nothing I want to have http:// at the beginning.

I can't figure out how to figure this out with a preg_match expression, or for the non-PHP inclined, a search and replace PHP function.

Community
  • 1
  • 1
Doug Smith
  • 29,668
  • 57
  • 204
  • 388
  • [What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please. – John Conde Feb 05 '13 at 01:38
  • reading http://www.regular-expressions.info/conditional.html might hold your answer. – Jerry Feb 05 '13 at 01:44

2 Answers2

1

You can use preg_replace_callback, and write a function to do that.

mario
  • 144,265
  • 20
  • 237
  • 291
0

Something like this should work if you want a regex solution.

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

Though i would probably use parse_url and put it back together.

Rob
  • 12,659
  • 4
  • 39
  • 56
  • My problem lies with a URL such as `www.stackoveflow.com` without any http:// or https:// – Doug Smith Feb 05 '13 at 02:19
  • 1
    did you even try it? `echo preg_replace('|^(?:http(s)?://)?(.+)$|', 'http\\1://\\2', 'www.stackoverflow.com');` – Rob Feb 05 '13 at 02:30