我想检查字符串的第一个和最后一个元素是否是字母数字字符,并且字符串的大小并不重要。 为了检查它我使用一个小脚本:
if(preg_match("/^\w\w$/", $_GET['eq'])){
echo "<h1>true</h1>";
}else{
echo "<h1>false</h1>";
}
但是如果输入包含超过2个字符,则表示为false。如何查看更大的字符串?在我看来/^\w\w$/
应该检查第一个和最后一个字符与字符串的大小无关。
答案 0 :(得分:2)
您必须匹配并忽略所有中间字符:/^\w.*\w$/
所以,你的代码必须是:
if(preg_match("/^\w.*\w$/", $_GET['eq'])){
echo "<h1>true</h1>";
}else{
echo "<h1>false</h1>";
}
答案 1 :(得分:2)
例如,您可以使用
^\w.*\w$
.*
匹配任何字符(行终止符除外)
答案 2 :(得分:2)
尝试以下方法:
if(preg_match("/^[^A-Za-z0-9]+|[^A-Za-z0-9]+$/", $_GET['eq'])){
echo "<h1>true</h1>";
}else{
echo "<h1>false</h1>";
}
您需要能够跳过中间的所有字符。
答案 3 :(得分:1)
你的正则表达式只匹配一个2个字符的字符串。试试这个(.*
将允许它在中间可选地扩展):
if(preg_match("/^\w.*\w$/", $_GET['eq'])){
echo "<h1>true</h1>";
}else{
echo "<h1>false</h1>";
}
答案 4 :(得分: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.