2012-04-16 75 views
2

我想只允許字母,數字,空格,unserscore和連字符。Preg_match驗證字符串中的特殊字符

到目前爲止,我認爲這會的preg_match做的工作:

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

但我只是意識到,特殊字符的字符串裏,不會產生錯誤。例如

你好「@£$喬

不會產生一個錯誤。是否有可能稍作改動,並使其工作,或者我需要另一種解決辦法?

回答

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("[email protected]");   // true 
/[^a-z0-9 _]+/i.test("hello\"@£$joe"); // true 
/[^a-z0-9 _]+/i.test("hello joe");  // false 
+0

謝謝,這樣做的工作! – 2by 2012-04-16 09:25:54

+0

非常感謝你@salman – 2018-01-27 11:02:00

0

你需要把^字符類之外:

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

一個^內(開頭)字符類就像一個人物角色否定者一樣。

+0

對不起,但這不起作用 – 2by 2012-04-16 08:01:26

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

使用正則表達式

+0

爲什麼不是把所有東西放在一個班級? '[-_ a-zA-Z0-9]' – ThiefMaster 2012-04-16 07:58:00

+0

對不起,但這也行不通 – 2by 2012-04-16 08:12:40

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"; 
} 
?> 
+1

對不起,但我無法得到這個工作 – 2by 2012-04-16 08:56:40

+0

可能你做了一些錯誤的事情,它在我的情況下工作正常。每個值都可以正常工作在回答中使用此編輯 – 2012-04-16 09:04:04

+0

嗯,是的,當我測試你的代碼時,它工作。但是,當使用PHP這現在可以工作:'if(preg_match('/^[a-z0-9 \ s \ -_] + $/i',$ name)){ $ error =「Name只能包含字母,數字,空格,\「_ \」和\「 - \」。「; }' – 2by 2012-04-16 09:22:35