Convert absolute to relative url with preg_replace

2020-07-10 10:30发布

(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).

4条回答
手持菜刀,她持情操
2楼-- · 2020-07-10 10:33

Try this regexp.

#^              The start of the string
(
   ://          Match either ://
   |            Or
   [^/]         Not a /
)*              Any number of times
#

And replace it with the empty string.

$pattern = '#^(://|[^/])+#';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
查看更多
祖国的老花朵
3楼-- · 2020-07-10 10:42

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

查看更多
叼着烟拽天下
4楼-- · 2020-07-10 10:48

I think you want the part of the URL after the hostname, you can use parse_url:

$path = parse_url($url, PHP_URL_PATH);

Note that this gets the whole of the URL after the hostname, so http://example.com/page/slug will give /page/slug.

查看更多
Fickle 薄情
5楼-- · 2020-07-10 10:51

I would just do this a little hacky way if you know your application. I would use a regex to search for

[a-z].([(com|org|net)])
查看更多
登录 后发表回答