no one special
no one special

Reputation: 1756

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!

Upvotes: 1

Views: 33

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

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.

Upvotes: 1

Related Questions