简体   繁体   中英

How to get last segment of the URL without GET variables in PHP?

Now I have it like so:

<?
  $url=$_SERVER['REQUEST_URI'];
  $requred_string= substr(strrchr($url, "/"), 1);
?>

and it returns the last segment, but it also returns all the ?p=y&g=x gibberish that I don't need. How can I slice off the $_GET variables?

You can use strtok to exclude the query strings:

$url = strtok($_SERVER['REQUEST_URI'], '?');
$requred_string = substr(strrchr($url, '/'), 1);
echo $requred_string;

Or as mentioned in the comments, parse_url will work also:

$requred_string = substr(strrchr(parse_url($url)['path'], '/'), 1); // PHP 5.4 or greater with dereference

这是一种更优雅的方式basename(parse_url($url, PHP_URL_PATH))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM