如何检查php字符串是否只包含英文字母和数字?

时间:2021-10-14 01:42:18

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来做。

7 个解决方案

#1


69  

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
}

#2


23  

if(ctype_alnum($string)) {
    echo "String contains only letters and numbers.";
}
else {
    echo "String doesn't contain only letters and numbers.";
}

#3


8  

You can use preg_match() function for example.

例如,您可以使用preg_match()函数。

if (preg_match('/[^A-Za-z0-9]+/', $str))
{
  // ok...
}

#4


6  

Have a look at this shortcut

看看这条捷径好吗

if(!preg_match('/[^\W_ ] /',$string)) {

}

the class [^\W_] matches any letter or digit but not underscore . And note the ! symbol . It will save you from scanning entire user input .

类(^ \ W_)匹配任何字母或数字但并不强调。,请注意!的象征。它将避免扫描整个用户输入。

#5


5  

if(preg_match('/[^A-Za-z0-9]+/', $str)) {
    // ...
}

#6


1  

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;
    }
}

#7


0  

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
}

#1


69  

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
}

#2


23  

if(ctype_alnum($string)) {
    echo "String contains only letters and numbers.";
}
else {
    echo "String doesn't contain only letters and numbers.";
}

#3


8  

You can use preg_match() function for example.

例如,您可以使用preg_match()函数。

if (preg_match('/[^A-Za-z0-9]+/', $str))
{
  // ok...
}

#4


6  

Have a look at this shortcut

看看这条捷径好吗

if(!preg_match('/[^\W_ ] /',$string)) {

}

the class [^\W_] matches any letter or digit but not underscore . And note the ! symbol . It will save you from scanning entire user input .

类(^ \ W_)匹配任何字母或数字但并不强调。,请注意!的象征。它将避免扫描整个用户输入。

#5


5  

if(preg_match('/[^A-Za-z0-9]+/', $str)) {
    // ...
}

#6


1  

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;
    }
}

#7


0  

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
}