如何在PHP中删除url的第一部分?

时间:2011-05-03 09:02:37

标签: php regex preg-replace

我想在PHP中删除网址的第一部分。例如:

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

必须是:

/sales
/myfolder/seconddir
/directory

因为动态的url,我认为我必须使用preg替换,但我不知道如何..有时url已被删除(参见上一个示例)。 怎么做?

3 个答案:

答案 0 :(得分:7)

这个parse_url有一个内置的php函数。

来自链接网站:

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

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>

以上示例将输出:

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

答案 1 :(得分:5)

尝试:

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

print_r($urlParts);

看看:

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

答案 2 :(得分:2)

您可以使用path info

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

输出:

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
)
祝你好运!