regex differentiating between ISBN-10 and ISBN-13

前端 未结 5 518
后悔当初
后悔当初 2020-12-11 00:52

I have an If-else statement which checks a string to see whether there is an ISBN-10 or ISBN-13 (book ID).

The problem I am facing is with the ISBN-10 check which o

5条回答
  •  离开以前
    2020-12-11 01:23

    Use ^ and $ to match beginning and end of string. By using the string delimiters, the order in which you test the 10 or the 13-digit codes will not matter.

    10 digits

    /^ISBN:(\d{9}(?:\d|X))$/
    

    13 digits

    /^ISBN:(\d{12}(?:\d|X))$/
    

    Note: According to http://en.wikipedia.org/wiki/International_Standard_Book_Number, it appears as though ISBNs can have a - in them as well. But based on the $str you're using, it looks like you've removed the hyphens before checking for 10 or 13 digits.

    Additional note: Because the last digit of the ISBN is used as a sort of checksum for the prior digits, regular expressions alone cannot validate that the ISBN is a valid one. It can only check for 10 or 13-digit formats.


    $isbns = array(
      'ISBN:1234567890',       // 10-digit
      'ISBN:123456789X',       // 10-digit ending in X
      'ISBN:1234567890123',    // 13-digit
      'ISBN:123456789012X',    // 13-digit ending in X
      'ISBN:1234'              // invalid
    );
    
    function get_isbn($str) {
       if (preg_match('/^ISBN:(\d{9}(?:\d|X))$/', $str, $matches)) {
          echo "found 10-digit ISBN\n";
          return $matches[1];
       }
       elseif (preg_match('/^ISBN:(\d{12}(?:\d|X))$/', $str, $matches)) {
          echo "found 13-digit ISBN\n";
          return $matches[1];
       }
       else {
          echo "invalid ISBN\n";
          return null;
       }
    }
    
    foreach ($isbns as $str) {
       $isbn = get_isbn($str);
       echo $isbn."\n\n";
    }
    

    Output

    found 10-digit ISBN
    1234567890
    
    found 10-digit ISBN
    123456789X
    
    found 13-digit ISBN
    1234567890123
    
    found 13-digit ISBN
    123456789012X
    
    invalid ISBN
    

提交回复
热议问题