Preg_match验证字符串中的特殊字符


Preg_match validating special chars inside a string

我只想允许字母、数字、空格、unserscore 和连字符。

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

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

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

你好"@£$joe

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

问题出在$符号上。您专门要求它匹配字符串的末尾。表达式 /[^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

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

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

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

/^([a-z]|[A-Z]|[0-9]| |_|-)+$/

使用此正则表达式

这里 拿这个:

/^[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 以检查是否为 true。

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

<?php

if(preg_match("/^[a-z0-9's'-_]+$/i","ASDhello-dasd  asddasd_dsad")){
    echo "true";
}
else{
    echo "false";
}
?>