5

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?

1
  • You should mark right answer in each of your questions, if there's any. Commented May 20, 2010 at 12:50

5 Answers 5

7

...

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

Output:

interesting_part
Sign up to request clarification or add additional context in comments.

2 Comments

I was just writing this as you posted :D
If 'something' does not have '/' inside then it's the best way to achieve it.
6

Try:

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

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

2 Comments

I don't know why somebody did "-1" on this. Its equivalent to exploding the thing. I pushed it back to 0 :)
People see regular expressions and they stab their author.
5

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

Comments

2

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));

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.