How to remove first part of url in PHP?

2019-06-21 08:24发布

问题:

I want to remove te first part of the url in PHP. Example:

http://www.domain.com/sales
http://otherdomain.org/myfolder/seconddir
/directory

must be:

/sales
/myfolder/seconddir
/directory

Because the url in dynamic, I think I have to do this with preg replace, but I don't know how.. And sometimes the url is already removed (see last example). How to do this?

回答1:

There is a built in php function for this parse_url.

From the linked website:

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

The above example will output:

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)
/path


回答2:

Try:

<?php
$url = 'http://otherdomain.org/myfolder/seconddir';
$urlParts = parse_url($url);

print_r($urlParts);

And have a look at:

http://php.net/manual/en/function.parse-url.php



回答3:

you could use path info:

<?php
print_r(pathinfo("http://www.domain.com/sales"));
print_r(pathinfo("http://otherdomain.org/myfolder/seconddir"));
print_r(pathinfo("/directory"));
?>

the output:

Array
(
    [dirname] => http://www.domain.com
    [basename] => sales
    [filename] => sales
)
Array
(
    [dirname] => http://otherdomain.org/myfolder
    [basename] => seconddir
    [filename] => seconddir
)
Array
(
    [dirname] => /
    [basename] => directory
    [filename] => directory
)

good luck!