所以,我在一个字符串中有这个URL:
http://www.domain.com/something/interesting_part/?somevars&othervars
Run Code Online (Sandbox Code Playgroud)
在PHP中,我怎么能摆脱所有interesting_part呢?
...
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];
Run Code Online (Sandbox Code Playgroud)
输出:
interesting_part
Run Code Online (Sandbox Code Playgroud)
尝试:
<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];
Run Code Online (Sandbox Code Playgroud)
您应该使用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 ...
Run Code Online (Sandbox Code Playgroud)