Get panel page ID before panel loads

A panel url can look like this:

http://localhost/kirby/2.4.1/panel/pages/projects/project-b/edit
http://localhost/kirby/2.4.1/panel/pages/projects/project-b/toggle
http://localhost/kirby/2.4.1/panel/pages/projects/project-b/edit/edit
http://localhost/kirby/2.4.1/panel/pages/projects/project-b/file/room.jpg/edit

From this I want to get the id, in this case projects/project-b. It would be easy if I let the panel load first but I have a plugin that loads before the panel.

Right now I’m using this to get the id and it looks kind of terrible.

$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = ( strstr($url, '/edit', true) ) ? strstr($url, '/edit', true) : $url;
$url = ( strstr($url, '/toggle', true) ) ? strstr($url, '/toggle', true) : $url;
$url = ( strstr($url, '/template', true) ) ? strstr($url, '/template', true) : $url;
$url = ( strstr($url, '/url', true) ) ? strstr($url, '/url', true) : $url;
$url = ( strstr($url, '/delete', true) ) ? strstr($url, '/delete', true) : $url;
$url = ( strstr($url, '/file/', true) ) ? strstr($url, '/file/', true) : $url;		
$id = str_replace(panel()->urls()->index() . '/pages/', '', $url);
echo $id;

It has a few pitfalls, like it’s possible to have a page end with /edit/edit and other things.

Is there a better way to do it? Maybe use some clever Kirby/Panel function to help me out?

Update

I’ve found a way to make it shorter, but the problem with the possibility that /edit could be a page still exists.

$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = preg_replace('/\/edit$/', '', $url);
$url = preg_replace('/\/toggle$/', '', $url);
$url = preg_replace('/\/template$/', '', $url);
$url = preg_replace('/\/url$/', '', $url);
$url = preg_replace('/\/delete$/', '', $url);
$id = ( strstr($url, '/file/', true) ) ? strstr($url, '/file/', true) : $url;
echo $id;

Update 2

Even shorter…

$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url = str_replace(panel()->urls()->index() . '/pages/', '', $url);
$url = substr($url, 0, strrpos( $url, '/'));
$id= ( strstr($url, '/file/', true) ) ? strstr($url, '/file/', true) : $url;
echo $id;