所以,我在字符串中有这个URL:
http://www.domain.com/something/interesting_part/?somevars&othervars
在PHP中,除了interesting_part
之外我怎么能摆脱它?
答案 0 :(得分:5)
...
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];
<强>输出:强>
interesting_part
答案 1 :(得分:5)
尝试:
<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];
答案 2 :(得分:4)
您应该使用parse_url对URL进行操作。首先解析它,然后做你想要的改变,例如,爆炸,然后把它放回去。
$uri = "http://www.domain.com/something/interesting_part/?somevars&othervars";
$uri_parts = parse_url( $uri );
/*
you should get:
array(4) {
["scheme"]=>
string(4) "http"
["host"]=>
string(14) "www.domain.com"
["path"]=>
string(28) "/something/interesting_part/"
["query"]=>
string(18) "somevars&othervars"
}
*/
...
// whatever regex or explode (regex seems to be a better idea now)
// used on $uri_parts[ "path" ]
...
$new_uri = $uri_parts[ "scheme" ] + $uri_parts[ "host" ] ... + $new_path ...
答案 3 :(得分:1)
如果有趣的部分始终是路径的最后一部分:
echo basename(parse_url($url, PHP_URL_PATH));
[+]请注意,这只会在index.php
之前没有?
或任何其他文件名时生效。这个适用于两种情况:
$path = parse_url($url, PHP_URL_PATH);
echo ($path[strlen($path)-1] == '/') ? basename($path) : basename(dirname($path));
答案 4 :(得分:0)
以下是使用parse_url()
覆盖特定部分的示例:
<?php
$arr = parse_url("http://www.domain.com/something/remove_me/?foo&bar");
$arr['path'] = "/something/";
printf("%s://%s%s?%s", $arr['scheme'], $arr['host'], $arr['path'], $arr['query']);