Convert absolute to relative url with preg_replace

(I searched and found many conversion questions regarding absolute URLs, but nothing for absolute relative.)

I would like to enter data from the form field and eventually get the relative url. Ideally, this could work with any of the following inputs and end /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 I don’t think about ... anymore?

Edit: I would also like this to work for something where the relative URL, for example. /page/post(i.e. something with more than one slash).

+5
source share
4 answers

parse_url, URL-. :

parse_url($url, PHP_URL_PATH)

FYI, , , : example.com/page-slug

+9

.

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

.

$pattern = '#^(://|[^/])+#';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
+1

, URL- , parse_url:

$path = parse_url($url, PHP_URL_PATH);

, URL- , http://example.com/page/slug /page/slug.

+1

, .

[a-z].([(com|org|net)])
0

All Articles