我在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.";
}
如果你需要检查某个字符串是否为英语,可以使用以下函数。可能会对某些人有所帮助。
function is_english($str)
{
if (strlen($str) != strlen(utf8_decode($str))) {
return false;
} else {
return true;
}
}
看看这个快捷方式
if(!preg_match('/[^\W_ ] /',$string)) {
}
class [^\W_]
匹配任何字母或数字,但不包括下划线。请注意!
符号。它可以避免扫描整个用户输入。
if(preg_match('/[^A-Za-z0-9]+/', $str)) {
// ...
}
if (preg_match('/^[\w\s?]+$/si', $string)) {
// input text is just English or Numeric or space
}
\w
匹配所有带有变音符号的字符,例如éèçàÀ...
。 - Totoif(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)
将字符串与正则表达式进行比较,例如:
if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
// $string contains only English letters and digits
}
$string = 'hi, how are you ?';
if (!preg_match('/[^A-Za-z0-9 #$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]+/', $string)) // '/[^a-z\d]/i' should also work.
{
echo 'english';
}else
{
echo 'non-english';
}