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("/[^\/]+$/", "http://www.codexpresslabs.blogspot.com/m/groups/view/test", $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: https://stackoverflow.com/a/1361752/4189000

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:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

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


$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

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