phpregexvalidationdigits

Validate that string is all digits and has a qualifying length


I want to validate a string only if it contains '0-9' chars with length between 7 and 9.

What I have is [0-9]{7,9} but this matches a string of ten chars too, which I don't want.


Solution

  • If you want to find 7-9 digit numbers inside a larger string, you can use a negative lookbehind and lookahead to verify the match isn't preceded or followed by a digit

    (?<![0-9])[0-9]{7,9}(?![0-9])
    

    This breaks down as

    If you simply want to ensure the entire string is a 7-9 digit number, anchor the match to the start and end with ^ and $

    ^[0-9]{7,9}$