regex differentiating between ISBN-10 and ISBN-13

前端 未结 5 557
后悔当初
后悔当初 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:26

    Switch the order of the if else block, also strip all whitespace, colons, and hyphens from your ISBN:

    //Replace all the fluff that some companies add to ISBNs
    $str = preg_replace('/(\s+|:|-)/', '', $str);
    
    if(preg_match("/^ISBN\d{12}(?:\d|X)$/", $str, $matches)){
       echo "ISBN-13 FOUND\n";
       //isbn returned will be 9780113411436
       return 1;
    }
    
    else if(preg_match("/^ISBN\d{9}(?:\d|X)$/", $str, $matches)){
       echo "ISBN-10 FOUND\n";  
       //isbn returned will be 9780113411
       return 0;
    }
    

提交回复
热议问题