2017-10-10 22 views
0

我想檢查一個字符串的第一個和最後一個元素是否是字母數字字符,並且它無關緊要。 要檢查它,我用一個小腳本:檢查一個字符串的第一個和最後一個元素是否是帶有模式的字母數字字符

if(preg_match("/^\w\w$/", $_GET['eq'])){ 
    echo "<h1>true</h1>"; 
}else{ 
    echo "<h1>false</h1>"; 
} 

但如果輸入包含超過2個字符,它說假的。我怎樣才能檢查一個更大的字符串?在我看來/^\w\w$/應該檢查第一個字符和最後一個字符無關,字符串有多大。

回答

1

你可以使用它,它會接受任何東西,但首字母和末字符將是字母數字。

if(preg_match('/^[A-Za-z0-9]{1}.*[A-Za-z0-9]{1}?$/i', $_GET['eq'])){ 
    echo "<h1>true</h1>"; 
}else{ 
    echo "<h1>false</h1>"; 
} 

表達解釋:

^ Beginning. Matches the beginning of the string, or the beginning of a line if the multiline flag (m) is enabled. 
[ Character set. Match any character in the set. 
A-Z Range. Matches a character in the range "A" to "Z" (char code 65 to 90). 
a-z Range. Matches a character in the range "a" to "z" (char code 97 to 122). 
0-9 Range. Matches a character in the range "0" to "9" (char code 48 to 57). 
] 
{1} Quantifier. Match 1 of the preceding token. 
. Dot. Matches any character except line breaks. 
* Star. Match 0 or more of the preceding token. 
[ Character set. Match any character in the set. 
A-Z Range. Matches a character in the range "A" to "Z" (char code 65 to 90). 
a-z Range. Matches a character in the range "a" to "z" (char code 97 to 122). 
0-9 Range. Matches a character in the range "0" to "9" (char code 48 to 57). 
] 
{1} Quantifier. Match 1 of the preceding token. 
? Lazy. Makes the preceding quantifier lazy, causing it to match as few characters as possible. 
$ End. Matches the end of the string, or the end of a line if the multiline flag (m) is enabled. 
1

您的正則表達式只能匹配2個字符的字符串。試試這一個,而不是(.*將允許它optionnally中間展開):

if(preg_match("/^\w.*\w$/", $_GET['eq'])){ 
    echo "<h1>true</h1>"; 
}else{ 
    echo "<h1>false</h1>"; 
} 
2

您必須匹配,並且忽略所有的中間人物:/^\w.*\w$/

所以,你的代碼必須是:

if(preg_match("/^\w.*\w$/", $_GET['eq'])){ 
    echo "<h1>true</h1>"; 
}else{ 
    echo "<h1>false</h1>"; 
} 
2

例如,你可以使用

^\w.*\w$ 

.*匹配任何字符(除行終止)

2

嘗試以下操作:

if(preg_match("/^[^A-Za-z0-9]+|[^A-Za-z0-9]+$/", $_GET['eq'])){ 
    echo "<h1>true</h1>"; 
}else{ 
    echo "<h1>false</h1>"; 
} 

你需要能夠跳過所有的字符在中間。

相關問題