$re = '/(?<!\d[ _-])(?<!\d)\d{4}(?:[_ -]?\d{4}){3}(?![_ -]?\d)/mx';
$str = '1234123412341234
(16 digits all together)
1234 1234 1234 1234
1234-1234-1234-1234
(card numbers with hyphens and spaces)
Find me 1234-1234-1234-1234 Find me (card numbers hidden amongst text)
What I\'m struggling to stop is the false positives I get, which I know are a direct result of achieving result number 4 above. The false positives being more than 16 digits which are clearly not card numbers. E.g
1) 1234-1234-1234-1234-1234';
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