$re = '/^[^\?#\s\d]*?(\d{4,7})(?:[^-\w\s\d]\S*?$|$)$/m';
$str = 'https://acme.com/cammins-1022
https://acme.com/francr-cameron-cummins-1022#home
https://acme.com/franchiummins-1025642?somthing
https://acme.com/francr-cameron-cummins-1022#home-321321-sadfg
https://acme.com/franchiummins-1025642?somthing-321321
https://acme.com/franchiummins-1025642-?somthing-321321
https://acme.com/cammins-1022321231231123';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php