I have a site and I would need to get one pages URL with PHP. The URL might be something www.mydomain.com/thestringineed/
or it can www.mydomain.com/thestringineed?data=1
or it can be www.mydomain.com/ss/thestringineed
So it's always the last string but I dont want to get anything after ?
You will use the parse_url function, then look at the path portion of the return.
like this:
$url='www.mydomain.com/thestringineed?data=1';
$components=parse_url($url);
//$mystring= end(explode('/',$components['path']));
// I realized after this answer had sat here for about 3 years that there was
//a mistake in the above line
// It would only give the last directory, so if there were extra directories in the path, it would fail. Here's the solution:
$mystring=str_replace( reset(explode('/',$components['path'])),'',$components['path']); //This is to remove the domain from the beginning of the path.
// In my testing, I found that if the scheme (http://, https://, ...) is present, the path does not include
//the domain. (it's available on it's own as ['host']) In that case it's just
// $mystring=$components['path']);
parse_url
should help you out.
<?php
$url = "http://www.mydomain.com/thestringineed/";
$parts = parse_url($url);
print_r($parts);
?>
parse_url()
is the function you are looking for. The exact part you want, can be received through PHP_URL_PATH
$url = 'http://php.net/manual/en/function.parse-url.php';
echo parse_url($url, PHP_URL_PATH);
use $_SERVER['REQUEST_URI']
it will return full current page url you can split it with '/' and use the last array index . it will be the last string
You can use:
$strings = explode("/", $urlstring);
Which will remove all the '/' in the url and return an array containing all the words.
$strings[count($strings)-1]
Now has the value of the string you need, but it may contain '?data=1' so we need to remove that:
$strings2 = explode("?", $strings[count($strings)-1]);
$strings2[0]
Has the string you are wanting out of the url.
Hope this Helps!
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
and your out put is
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path