davidlee
davidlee

Reputation: 6167

verify string with preg_match

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

Upvotes: 1

Views: 3871

Answers (3)

Steve Smith
Steve Smith

Reputation: 21

Try this instead, I've tested it as a spam filter on my site.

if (!preg_match("/^[0-9a-zA-Z]{5,80}$/D", "$name")) 
{
die("Error Occured : Please Enter Your Name Before Attempting to Send Message");
}

Upvotes: 1

rubber boots
rubber boots

Reputation: 15184

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

Upvotes: 1

Gumbo
Gumbo

Reputation: 655239

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].

Upvotes: 7

Related Questions