【问题标题】:php regex , preg match for special charactersphp regex , preg 匹配特殊字符
【发布时间】:2021-03-27 05:18:04
【问题描述】:

如果字符串有特殊字符,如何preg_match()?

字符串只接受字母和数字,不接受@ # $ ^ & * ( ) _ + ! { } : "等你能想到的特殊字符。

$specialCharacterRegex = "";

if(preg_match($specialCharacterRegex, $last_name, $match)){
    echo ("<script LANGUAGE='JavaScript'>
    window.alert('Invalid last name. Please check, make sure special character...');
    window.location.href='./../MEMBERS/members.php';
    </script>");
}

【问题讨论】:

  • 为您想要允许的字符创建一个否定字符类可能更容易,例如$specialCharacterRegex = "/[^A-Za-z0-9]/";
  • $specialCharacterRegex = "/\\W/";
  • @Toto 这将允许_,这是 OP 不想要的。
  • @Nick: $specialCharacterRegex = "/[\\W_]/"; ;-)

标签: php regex preg-match


【解决方案1】:

你可以这样检查,

$string = "hai1@";
echo preg_match('/^[a-zA-Z0-9]+$/', $string);

如果你得到 0 那么它有特殊字符 如果为 1 则只有数字和字母符合预期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2010-11-07
    • 1970-01-01
    相关资源
    最近更新 更多