no one special no one special - 1 month ago 6
PHP Question

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!

Answer

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.

Comments