简体   繁体   中英

How to remove first part of url in PHP?

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?

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM