Search code examples
phppreg-match

Understanding preg_match


I would like to check if string consists only of small letters or underscores. Does the following returns true if string meets this condition? Is any better way to do this?

preg_match('/[^a-z_]/', $category_address)

Thanks!


Solution

  • Use a + quantifier with anchors:

    preg_match('/\A[a-z_]+\z/', $category_address)
    

    The pattern matches:

    • \A - start of string
    • [a-z_]+ - 1 or more (due to the greedy quantifier +) characters defined in the character class: either lowercase ASCII letters or _
    • \z - the very end of string

    If an empty string should be matched, too, replace the + quantifier with a * one that matches zero or more occurrences of the quantified subpattern.