2017-10-10 46 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>"; 
} 

你需要能够跳过所有的字符在中间。

相关问题