如何检查 php 字符串是否只包含英文字母和数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9351306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check, if a php string contains only english letters and digits?
提问by Danny Fox
In JS I used this code:
在 JS 中,我使用了以下代码:
if(string.match(/[^A-Za-z0-9]+/))
but I don't know, how to do it in PHP.
但我不知道,如何在 PHP 中做到这一点。
回答by Frosty Z
Use preg_match().
使用preg_match()。
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
// string contains only english letters & digits
}
回答by vineeth
if(ctype_alnum($string)) {
echo "String contains only letters and numbers.";
}
else {
echo "String doesn't contain only letters and numbers.";
}
回答by evilone
You can use preg_match()function for example.
例如,您可以使用preg_match()函数。
if (preg_match('/[^A-Za-z0-9]+/', $str))
{
// ok...
}
回答by kushalvm
Have a look at this shortcut
看看这个快捷方式
if(!preg_match('/[^\W_ ] /',$string)) {
}
the class [^\W_]
matches any letter or digitbut not underscore . And note the !
symbol . It will save you from scanning entire user input .
将class [^\W_]
匹配任何字母或数字,但没有下划线。并注意!
符号 。它将使您免于扫描整个用户输入。
回答by Vitamin
if(preg_match('/[^A-Za-z0-9]+/', $str)) {
// ...
}
回答by shakee93
if you need to check if it is English or not. you could use below function. might help someone..
如果您需要检查它是否是英语。您可以使用以下功能。可能会帮助某人..
function is_english($str)
{
if (strlen($str) != strlen(utf8_decode($str))) {
return false;
} else {
return true;
}
}
回答by Ramin Rabiee
if (preg_match('/^[\w\s?]+$/si', $string)) {
// input text is just English or Numeric or space
}
回答by user3439891
if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
// $string constains both string and integer
}
The carrot was in the wrong place so it would have search for everything but what is inside the square brackets. When the carrot is outside it searches for what is in the square brackets.
胡萝卜在错误的位置,所以它会搜索除方括号内的内容之外的所有内容。当胡萝卜在外面时,它会搜索方括号中的内容。
回答by Saurabh
PHP can compare a string to a regular expression using preg_match(regex, string)
like this:
PHP 可以使用preg_match(regex, string)
如下方式将字符串与正则表达式进行比较:
if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
// $string contains only English letters and digits
}