Search code examples
phpregexisbn

Use regex to verify an ISBN number


I need a regex to verify ISBN number entered by user.

ISBN must be a string contains only: [10 or 13 digits] and hyphens

I tried ^[\d*\-]{10}|[\d*\-]{13}$ but it doesn't work.

My regex only matches: 978-1-5661, 1-56619-90, 1257561035

It should returns the results below:

"978-1-56619-909-4 2" => false
"978-1-56619-909-4" => true
"1-56619-909-3 " => false
"1-56619-909-3" => true
"isbn446877428ydh" => false
"55 65465 4513574" => false
"1257561035" => true
"1248752418865" => true

I really appreciate any help.


Solution

  • You can use this regex with a positive lookahead:

    ^(?=(?:\D*\d){10}(?:(?:\D*\d){3})?$)[\d-]+$
    

    RegEx Demo

    (?=(?:\D*\d){10}(?:(?:\D*\d){3})?$) is a positive lookahead that ensures we have 10 or 13 digits in the input.