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

So, I have this url in the line:

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

in PHP, how can I get rid of everyone except interesting_part ?

+4
source share
5 answers

...

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

Conclusion:

 interesting_part 
+5
source

Try:

 <?php $url = 'http://www.domain.com/something/interesting_part/?somevars&othervars'; preg_match('`/([^/]+)/[^/]*$`', $url, $m); echo $m[1]; 
+5
source

You must use parse_url to perform operations with the url. First analyze it, then make the changes you want using, for example, an explosion, then bring 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 ... 
+4
source

If the interesting part is always the last part of the path:

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

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

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

The following is an example of using parse_url() to override a 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
source

Source: https://habr.com/ru/post/1310364/


All Articles