简体   繁体   中英

PHP, Regex - how to disallow non-alphanumeric characters

I'm trying to make a regex that would allow input including at least one digit and at least one letter (no matter if upper or lower case) AND NOTHING ELSE. Here's what I've come up with:

<?php
    if (preg_match('/(?=.*[a-z]+)(?=.*[0-9]+)([^\W])/i',$code)) {
    echo "=)";
    } else {
    echo "=(";
    }
?>

While it gives false if I use only digits or only letters, it gives true if I add $ or # or any other non-alphanumeric sign. Now, I tried putting ^\\W into class brackets with both az and 0-9, tried to use something like ?=.*[^\\W] or ?>! but I just can't get it work. Typing in non-alphanums still results in true. Halp meeee

您需要使用锚,使其与整个字符串匹配。

^(?=.*[a-z]+)(?=.*[0-9]+)(\w+)$

Since you are using php, why even use regex at all. You can use ctype_alnum()

http://php.net/manual/en/function.ctype-alnum.php

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