null
null

Reputation: 2078

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

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?

Upvotes: 5

Views: 5875

Answers (5)

kenorb
kenorb

Reputation: 166419

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

Upvotes: 0

Kamil Szot
Kamil Szot

Reputation: 17817

Try:

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

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

Upvotes: 6

Ondrej Slint&#225;k
Ondrej Slint&#225;k

Reputation: 31910

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

Upvotes: 5

dev-null-dweller
dev-null-dweller

Reputation: 29462

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

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382696

...

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

Output:

interesting_part

Upvotes: 7

Related Questions