Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert absolute to relative url with preg_replace

(I searched, and found lots of questions about converting relative to absolute urls, but nothing for absolute to relative.)

I'd like to take input from a form field and end up with a relative url. Ideally, this would be able to handle any of the following inputs and end up with /page-slug.

  • http://example.com/page-slug
  • http://www.example.com/page-slug
  • https://example.com/page-slug
  • https://www.example.com/page-slug
  • example.com/page-slug
  • /page-slug
  • And maybe more I'm not thinking of...?

Edit: I'd also like this to work for something where the relative url is e.g. /page/post (i.e. something with more than one slash).

like image 424
Travis Northcutt Avatar asked Aug 10 '11 20:08

Travis Northcutt


1 Answers

Take a look at parse_url if you are always working with URLs. Specifically:

parse_url($url, PHP_URL_PATH)

FYI, I tested it against all your input, and it worked on all except: example.com/page-slug

like image 158
steveo225 Avatar answered Oct 05 '22 06:10

steveo225