Get Prefix From URL in PHP | Codexpress Programming Blog - Tutorials about, PHP, MySQL and Web Development

Get Prefix From URL in PHP

Get last word from URL after a slash in PHP

Using regex:

preg_match("/[^\/]+$/", "", $matches);
$last_word = $matches[0]; // test

Use basename with parse_url:

echo basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

I used this:

$lastWord = substr($url, strrpos($url, '/') + 1);

Thanks to:

You can use explode but you need to use / as delimiter:

$segments = explode('/', $_SERVER['REQUEST_URI']);

Note that $_SERVER['REQUEST_URI'] can contain the query string if the current URI has one. In that case you should use parse_url before to only get the path:


And to take trailing slashes into account, you can use rtrim to remove them before splitting it into its segments using explode. So:


$segments = explode('/', rtrim($_SERVER['REQUEST_URI_PATH'], '/'));