开发者

verify string with preg_match

I have question that seems simple to you a开发者_StackOverflow社区ll 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


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


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


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜