banditKing
banditKing

Reputation: 9579

php regular expression for 4 characters

I am trying to construct a regular expression for a string which can have 0 upto 4 characters. The characters can only be 0 to 9 or a to z or A to Z.

I have the following expression, it works but I dont know how to set it so that only maximum of 4 characters are accepted. In this expression, 0 to infinity characters that match the pattern are accepted.

'([0-9a-zA-Z\s]*)'

Upvotes: 0

Views: 3525

Answers (4)

KingCrunch
KingCrunch

Reputation: 131861

You can avoid regular expressions completely.

if (strlen($str) <= 4 && ctype_alnum($str)) {
   // contains 0-4 characters, that are either letters or digits
}

ctype_alnum()

Upvotes: 0

Alan Moore
Alan Moore

Reputation: 75222

If you want to match a string that consists entirely of zero to four of those characters, you need to anchor the regex at both ends:

'(^[0-9a-zA-Z]{0,4}$)'

I took the liberty of removing the \s because it doesn't fit your problem description. Also, I don't know if you're aware of this, but those parentheses do not form a group, capturing or otherwise. They're not even part of the regex; PHP is using them as regex delimiters. Your regex is equivalent to:

'/^[0-9a-zA-Z]{0,4}$/'

If you really want to capture the whole match in group #1, you should add parentheses inside the delimiters:

'/(^[0-9a-zA-Z]{0,4}$)/'

... but I don't see why you would want to; the whole match is always captured in group #0 automatically.

Upvotes: 1

Paul
Paul

Reputation: 141839

You can use { } to specify finite quantifiers:

[0-9a-zA-Z\s]{0,4}

http://www.regular-expressions.info/reference.html

Upvotes: 1

Joey
Joey

Reputation: 354436

You can use {0,4} instead of the * which will allow zero to four instances of the preceding token:

'([0-9a-zA-Z\s]{0,4})'

(* is actually the same as {0,}, i.e. at least zero and unbounded.)

Upvotes: 3

Related Questions