Break this down into two parts:
First, we create a variable that stores that last-visited page URL, like this:
$prev_url = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
Then, you could either use substr and strpos to trim down everything between ?= and the / after the ID number. like this:
$prev_url="http://www.yoursite.com/?p=123";
$id_block = substr($prev_url, strpos($prev_url, "?p=")+1);
$id = substr($id_block, 0, strpos($id_block, "https://wordpress.stackexchange.com/"));
.. Or, you could use jQuery/Javascript to achieve the same.
I haven’t tested this but it should work – let me know how it does!
Good luck 😉