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
?
<? php $url = 'http://www.example.com/news?q=string&f=true&id=1233&sort=true'; $values = parse_url($url); $host = explode('. ',$values['host']); echo $host[1]; ?>
parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it. It parse an URL and return an associative array which contains its various components. parse_str() Function: The parse_str() function is used to parse a query string into variables.
Get Last URL Segment If you want to get last URI segment, use array_pop() function in PHP.
Which command will extract the domain suffix? PHP's parse_url function makes it easy to extract the domain, path and other useful bits of information from a full URL.
...
$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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With