2

我只想允许使用字母、数字、空格、无衬线和连字符。

到目前为止,我认为这个 preg_match 可以完成这项工作:

if(preg_match('/[^a-z0-9 _]+$/i', $name)) {
$error = "Name may only contain letters, numbers, spaces, \"_\" and \"-\".";
}

但我刚刚意识到字符串中的特殊字符不会产生错误。例如

你好”@£$joe

不会产生错误。是否可以进行一些更改并使其正常工作,还是我需要其他解决方案?

4

4 回答 4

3

问题出在$符号上。您特别要求它匹配字符串的结尾。表达式/[^a-z0-9 _]+$/i将不匹配hello"@£$joe,因为joe匹配[a-z0-9 _]+$; 所以当你否定课程时它显然不会匹配。删除$符号,一切都会如预期的那样:

if(preg_match('/[^a-z0-9 _]+/i', $name)) {
// preg_match will return true if it finds 
// a character *other than* a-z, 0-9, space and _
// *anywhere* inside the string
}

通过将这些行一一粘贴到 JavaScript 控制台中,在浏览器中对其进行测试:

/[^a-z0-9 _]+/i.test("@hello");        // true
/[^a-z0-9 _]+/i.test("joe@");          // true
/[^a-z0-9 _]+/i.test("hello\"@£$joe"); // true
/[^a-z0-9 _]+/i.test("hello joe");     // false
于 2012-04-16T09:15:26.883 回答
0

您需要将字符类带到^外部:

if(preg_match('/^[a-z0-9 _]+$/i', $name)) {

一个字符类的^内部(在开始时)就像一个字符类的否定符。

于 2012-04-16T07:53:50.027 回答
0

拿这个:

/^[a-z0-9\s\-_]+$/i

我用虚拟数据测试了这个表达式。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function valueanalysis(form){
    var vals = form.vals.value;

    alert(/^[a-z0-9\s\-_]+$/i.test(vals));

    return false;
}
</script>
</head>

<body>
<form onsubmit="return valueanalysis(this);">
<input type="text" name="vals"/>
<input type="submit" value="Check" />
</form>
</body>
</html>

在 html 文件中使用此代码通过填充值来检查验证,然后按 Enter 检查是否为真。

注意:- 所有语言的正则表达式都是相同的。

<?php


if(preg_match("/^[a-z0-9\s\-_]+$/i","ASDhello-dasd  asddasd_dsad")){
    echo "true";
}
else{
    echo "false";
}
?>
于 2012-04-16T08:43:55.393 回答
0
/^([a-z]|[A-Z]|[0-9]| |_|-)+$/

使用这个正则表达式

于 2012-04-16T07:55:25.103 回答