$re = '/(?<=_)(\d{4})(?=_?|\.p\d)/';
$str = '14-5678_jobname_0123_.p1.PDF
14-5678_jobname_0123_.p2.PDF
14-5678_jobname_0125_.p1.PDF
Weired_filename_0123_bla_14-5678_jobname.p1.PDF
Weired_filename_0123_bla_14-5678_jobname.p2.PDF
Weired_filename_0125_bla_14-5678_jobname.p1.PDF
14-5678_jobname_0123.p1.PDF
14-5678_jobname_0123.p2.PDF
14-5678_jobname_0125.p1.PDF
0123_14-5678_jobname.p1.PDF
0123_14-5678_jobname.p2.PDF
0125_14-5678_jobname.p1.PDF
jobname_0123_14-5678.p1.PDF
jobname_0123_14-5678.p2.PDF
jobname_0125_14-5678.p1.PDF';
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