[英]How to check, if a php string contains only english letters and digits?
在JS中我使用了这段代码:
if(string.match(/[^A-Za-z0-9]+/))
但我不知道,如何在PHP中做到这一点。
使用preg_match() 。
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
// string contains only english letters & digits
}
if(ctype_alnum($string)) {
echo "String contains only letters and numbers.";
}
else {
echo "String doesn't contain only letters and numbers.";
}
例如,您可以使用preg_match()函数。
if (preg_match('/[^A-Za-z0-9]+/', $str))
{
// ok...
}
看看这个快捷方式
if(!preg_match('/[^\W_ ] /',$string)) {
}
class [^\\W_]
匹配任何字母或数字但不匹配下划线。 请注意!
符号。 它将使您免于扫描整个用户输入。
if(preg_match('/[^A-Za-z0-9]+/', $str)) {
// ...
}
如果你需要检查它是否是英语。 你可以使用以下功能。 可能会帮助别人..
function is_english($str)
{
if (strlen($str) != strlen(utf8_decode($str))) {
return false;
} else {
return true;
}
}
if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
// $string constains both string and integer
}
胡萝卜是在错误的地方所以它会搜索除了方括号内的所有东西。 当胡萝卜在外面时,它会搜索方括号中的内容。
PHP可以使用preg_match(regex, string)
将字符串与正则表达式进行比较preg_match(regex, string)
如下所示:
if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
// $string contains only English letters and digits
}
if (preg_match('/^[\w\s?]+$/si', $string)) {
// input text is just English or Numeric or space
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.