开发者

How extract part of an URL in PHP to remove specific part?

开发者 https://www.devze.com 2022-12-31 15:48 出处:网络
So, I have this URL 开发者_JS百科in a string: http://www.domain.com/something/interesting_part/?somevars&othervars

So, I have this URL 开发者_JS百科in a string:

http://www.domain.com/something/interesting_part/?somevars&othervars

in PHP, how I can get rid of all but interesting_part?


...

$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];

Output:

interesting_part


Try:

<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';

preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];


You should use parse_url to do operations with URL. First parse it, then do changes you desire, using, for example, explode, then put it back together.

$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 ... 


If the interesting part is always last part of path:

echo basename(parse_url($url, PHP_URL_PATH));

[+] please note that this will only work without index.php or any other file name before ?. This one will work for both cases:

$path = parse_url($url, PHP_URL_PATH);
echo  ($path[strlen($path)-1] == '/') ? basename($path) : basename(dirname($path));


Here is example using parse_url() to override the specific part:

<?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']);
0

精彩评论

暂无评论...
验证码 换一张
取 消