tags:

views:

45

answers:

2

Hi all,

I have question that seems simple to you all but can't really get it. encounter warning till now.

May I know how can i accept a string with integers 0-9 and alpha a-zA-Z but minimum 5 characters and maximum 15 characters with preg_match. Thanks

+4  A: 

Try this:

preg_match('/^[0-9a-zA-Z]{5,15}$/D', $str)

Here ^ marks the begin and $ the end of the string (the D modifier is to let $ match only the end of the line without an ending line break). That means the whole string must be matched by the pattern [0-9a-zA-Z]{5,15} that describes a sequence of 5 to 15 characters of the character class [0-9a-zA-Z].

Gumbo
this accepts "gumbo\n" ))
stereofrog
@stereofrog: Fixed that.
Gumbo
@gumbo thanks. it works perfect
benmsia
@gumbo can i use [:alnum:] instead of a-z0-9?
benmsia
@benmsia: Yes, you can use `[:alnum:]` (see http://php.net/regexp.reference.character-classes).
Gumbo
@gumbo (regarding [:alnum:]) I'd guess rather **not**. See http://www.php.net/manual/en/reference.pcre.pattern.posix.php
rubber boots
+1  A: 

You said in your posting

how can i accept a string with integers 0-9 AND alpha a-zA-Z but

If that AND is a locigal and reads "letters && numbers", this gets more complicated:

 ...

 $nd = preg_match_all('/\d/', $text, $m);        # count numbers
 $na = preg_match_all('/[a-zA-Z]/', $text, $m);  # count characters
 $nn = $na + $nd;                                # must be like strlen($text)

 if($nn==strlen($text) && $nn>=5 && $nn<=15 && $na && $nd)
    echo "$text ok";
  else
    echo "$text not ok";

 ...

Regards

rbo

rubber boots
its too complicated. pls refer to gumbo's . thanks..
benmsia
@benmisa, this is for a completely different use case, like in password generation if you have to have numbers and letters, but at least a number AND at least a letter: AABBB wrong, 12222 wrong, AABB1 correct.
rubber boots
@rub ic. cool.. thanks for your effort. =)
benmsia