tags:

views:

136

answers:

4

So, I have this url in a string:

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

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

+4  A: 

...

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

Output:

interesting_part
Sarfraz
I was just writing this as you posted :D
Ben Dauphinee
oh, clever! I'm trying this right now, thanks a lot!
achairapart
@achairapart: You are welcome :)
Sarfraz
If 'something' does not have '/' inside then it's the best way to achieve it.
Kamil Szot
+2  A: 
<?                                                                                                                                                       

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

preg_match('`/([^/]+)/[^/]*$`', $url, $m);                                                                                                               
echo $m[1];                                                                                                                                              
Kamil Szot
I don't know why somebody did "-1" on this. Its equivalent to exploding the thing. I pushed it back to 0 :)
naugtur
People see regular expressions and they stab their author.
erisco
+1  A: 

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));
dev-null-dweller
+2  A: 

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&amp;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 ... 
Ondrej Slinták
yeah, that's right: first parse_url, then explode path as @Sarfraz suggested. thank you all for the help, so much feedback!
achairapart
Edited with some new stuff, for the greater good!
Ondrej Slinták