在PHP中获取URL的一部分并不完全正常

I've this code here:

$url = 'https://www.my-page.de/account/show/4913';

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

This returns me the needed id:

4913

Now the problem begins. In some cases the URL looks like this:

$url = 'https://www.my-page.de/account/show/4913/';

$url = 'https://www.my-page.de/account/show/4913/?conversationId=xxx';

This means that my code don't works anymore. So is there any way to be 100 % sure that I always get my ID from the URL? The ID is always at the same position from the beginning on but the end can be different.

Update

When I've this code here I'm getting not the last part anymore. Any idea why and how to fix this?:

$url = 'https://my-page.de/account/show/4913/';
$id = basename( dirname( $url ) );

I just want to be sure that it works in every situation. In this case the selected part is:

show

You could use functions that are meant for directories and/or URLs:

echo basename(dirname($url));
//or 
echo basename(pathinfo($url, PATHINFO_DIRNAME));
//or
echo basename(parse_url($url, PHP_URL_PATH));

The last one may return the filename if you had https://www.my-page.de/account/show/4913/index.php so you would want to use:

echo basename(dirname(parse_url($url, PHP_URL_PATH)));

Lot's of possibilities depending on what you need. The point is that there are specific functions for working with directories, filenames and URLs so that you don't have to treat them as just strings that have no meaning but unlimited possibilities..

Just use explode() to turn it into an array, then get the 5th item to get the id:

<?php
    $url = 'https://www.my-page.de/account/show/4913/?conversationId=xxx&trey=trey';
    $arr = explode('/', $url);

    $id = $arr[5];

    echo '<pre>'. print_r($id, 1) .'</pre>';

then it doesn't matter how many query params there are, they'll always be last

refs:

https://www.php.net/manual/en/function.explode.php