简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM