PHP check, whether a string is a valid ASIN


To check, whether a string is a valid ASIN, there are 2 possible rules for ASINs:

  • a “B” followed by 2 digits and 7 alphanumeric values
  • a special ISBN Vairiante: 9 digits and at the end either a “X” or another digit (very rare)

The regular expression encapsulated in a function in PHP is:

function isAsin($string){
    $ptn = "/B[0-9]{2}[0-9A-Z]{7}|[0-9]{9}(X|0-9])/";
    if(preg_match($ptn, $string, $matches)){
        return true;
    }
}

To test the regex, I have used the following code:

$testAsins = array("B223213FCF","232342342X", "A223213FCF");
foreach ($testAsins as $testAsin)
{
    if(isAsin($testAsin)){
        echo $testAsin." is ASIN"."<br>";
    }
}

The output of the script is:

B223213FCF is ASIN
232342342X is ASIN
  1. the pattern in ‘isAsin’ is missing a opening square brace at the last part:
    It must be “/B[0-9]{2}[0-9A-Z]{7}|[0-9]{9}(X|[0-9])/”. You might test with an example of a fully numeric ISBN as well, e.g. ’3898127052′