Validate a Credit Card Number

This code snippet is a regular expression which checks or validates a credit card number.

The Expression

^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$

This regular expression will match any of the following credit card number formats:

  • 0000-0000-0000-0000
  • 0000-0000-0000-000
  • 0000-0000-0000-00
  • 0000 0000 0000 0000
  • 0000 0000 0000 000
  • 0000 0000 0000 00
  • 0000000000000000
  • 000000000000000
  • 00000000000000

Validate Function

Here is a quick and simple validation function for a credit card number using the regular expression above and PHP’s preg_match() function:

function validate_credit_card_number( $string ) {
    if ( preg_match( '/^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$/', $string ) ) {
        return TRUE;
    } else {
        return FALSE;
    }
}

Modify the Data

$string = "1234123412341234";
preg_match( '/^([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{4})[-|s]*([0-9]{2,4})$/', $string, $matches );
$new_string = $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '-' . $matches[4];

// New String:
// 1234-1234-1234-1234