Get characters after last / in url

Very simply:

$id = substr($url, strrpos($url, "https://stackoverflow.com/") + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.


As mentioned by redanimalwar if there is no slash this doesn’t work correctly since strrpos returns false. Here’s a more robust version:

$pos = strrpos($url, "https://stackoverflow.com/");
$id = $pos === false ? $url : substr($url, $pos + 1);

Leave a Comment