我是PHP的新手,也是正则表达式的新手。我目前正在尝试编写一个正则表达式,以确保字符都是Alpha数字,并且接受其他字符。我想接受áéíñóúüÁÉÍÑÓÚÜ和@。+ - 。接受所有字母数字字符和符号@。+ - 。我使用表达式:
if (!preg_match("!^[\w@.-]*$!")
此外,在我继续之前,我想补充一下。这些是从表单输入中获取的值,它们应该都是一个单词短语(如无空格中)。好的,现在继续! :D现在我想抓住角色áéíñóúüÁÉÍÑÓÚÜ。当我使用表达式时:
if (!preg_match("/[\wáéíñóúüÁÉÍÑÓÚÜ@.\+-].*/")
它似乎没有用,有人可以帮忙吗?如果你感到困惑,或者说措辞不好,那就问问我会改写它:)
更新
我的表情:
if (!preg_match("!^[\w@.-]*$!")
确实有效,另一个无效。谢谢! :)
更新2
现在,当我尝试表达式时:
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {
输入michael.jonesáéí@gmail.com会引发错误。它引发的错误是“电子邮件包含受限制的字符”。因为我说它。这是我正在使用的具体代码:
<?php
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {
?>
<div id="allinputboxerror" class="col-xs-12"> Email contains restricted characters.</div>
<?php } ?>
}
以下是我正在使用的所有代码:
<?php
if ($_POST) {
$emailtest1 = False;
$emailtest2 = False;
$emailtest3 = False;
$emailtest4 = False;
$emailtest5 = False;
// Test #1 - Makes sure there is a input
if(empty($_POST['email'])) {
?>
<div id="allinputboxerror" class="col-xs-12"> Please enter your email. </div>
<?php
}
else {
$emailtest1 = True;
// Test #2 - Makes sure it does not already exist
$usernamequery = "SELECT 1 FROM users WHERE email = :email";
$usernameparams = array(':email' => $_POST['email']);
try{
$emailstmt = $connection->prepare($usernamequery);
$emailresult = $emailstmt->execute($usernameparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$emailcolumns = $emailstmt->fetch();
if($emailcolumns){
?>
<div id="allinputboxerror" class="col-xs-12"> This email already exists. </div>
<?php
}
else {
$emailtest2 = True;
// Test #3 - Makes sure it fits the length requirements
if(strlen($email) < 5 ) {
?>
<div id="allinputboxerror" class="col-xs-12"> Email is to short. </div>
<?php
}
elseif(strlen($email) > 75 ) {
?>
<div id="allinputboxerror" class="col-xs-12"> Email is to long. </div>
<?php
}
else {
$emailtest3 = True;
// Test #4 - Makes sure it does not have any restricted characters
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~", $email)) {
?>
<div id="allinputboxerror" class="col-xs-12"> Email contains restricted characters. </div>
<?php
}
else {
$emailtest4 = True;
// Test #5 - Makes sure the email is valid
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
?>
<div id="allinputboxerror" class="col-xs-12"> Not a valid email. </div>
<?php
}
else {
$emailtest5 = True;
// Final Check
if (($emailtest1 = True) and ($emailtest2 = True) and ($emailtest3 = True) and ($emailtest4 = True) and ($emailtest5 = True)) {
// Email is valid! :D
}
else {
?>
<div id="allinputboxerror" class="col-xs-12"> There is a error. </div>
<?php
}
}
}
}
}
}
}
?>
答案 0 :(得分:2)
正则表达式接受所有字母数字字符和符号@。+ - 。
^[\p{L}\p{N}@+.-]+$
您的正则表达式^[\w@.-]*$
与重音字符不匹配。即\w
只匹配英文字母,数字0-9
加上下划线符号。
\p{L}
匹配来自任何语言的任何类型的信件
\p{N}
匹配任何脚本中的任何数字字符。
+
将重复前一个标记一次或多次。我建议您使用+
而不是*
,因为*
重复前一个令牌零次或多次。所以它也匹配空字符串。
<强>更新强>
您需要包含unicode修饰符u
,以便\p{L}
匹配重音字符。
if (!preg_match("~^[\p{L}\p{N}@+._-]+$~u", $email)) {