Get part of URL with PHP

2019-07-31 09:30发布

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 ?

标签: php url
6条回答
Animai°情兽
2楼-- · 2019-07-31 10:12

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']);
查看更多
萌系小妹纸
3楼-- · 2019-07-31 10:17
<?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
查看更多
萌系小妹纸
4楼-- · 2019-07-31 10:23

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

查看更多
别忘想泡老子
5楼-- · 2019-07-31 10:25

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);
查看更多
祖国的老花朵
6楼-- · 2019-07-31 10:28

parse_url should help you out.

<?php
   $url = "http://www.mydomain.com/thestringineed/";
   $parts = parse_url($url);

   print_r($parts);
?>
查看更多
Explosion°爆炸
7楼-- · 2019-07-31 10:28

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!

查看更多
登录 后发表回答