只允许字符串中的某些字符

时间:2021-08-03 18:29:19

I have been looking for a way to create a function to check if a string contains anything other than lower case letters and numbers in it, and if it does return false. I have searched on the internet but all I can find is old methods that require you to use functions that are now deprecated in PHP5.

我一直在寻找一种方法来创建一个函数来检查字符串是否包含除小写字母和数字之外的任何内容,以及它是否返回false。我在互联网上搜索过,但我找到的只是旧方法,要求你使用PHP5中现已弃用的函数。

3 个解决方案

#1


2  

function check_input( $text ) {
  if( preg_match( "/[^a-z0-9]/", $text ) ) {
    return false;
  }
  else {
    return true;
  }
}

#2


1  

Use a regex. Use preg_match().

使用正则表达式。使用preg_match()。

$matches = preg_match('/[^a-z0-9]/', $string);

So now if $matches has 1, you know the $string contains bad characters. Otherwise $matches is 0, and the $string is OK.

所以现在如果$ matches有1,你知道$ string包含坏字符。否则$ matches为0,$ string为OK。

#3


0  

To mixen things up a bit

混合了一点东西

<?
$input = "hello world 123!";
$digits = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");

if (ctype_alnum($input))
{
    if (ctype_lower(str_replace($digits, "", $input)))
    {
        // Input is only lowercase and digits
    }
}
?>

But regex is probably the way to go here! =)

但正则表达式可能是去这里的方式! =)

#1


2  

function check_input( $text ) {
  if( preg_match( "/[^a-z0-9]/", $text ) ) {
    return false;
  }
  else {
    return true;
  }
}

#2


1  

Use a regex. Use preg_match().

使用正则表达式。使用preg_match()。

$matches = preg_match('/[^a-z0-9]/', $string);

So now if $matches has 1, you know the $string contains bad characters. Otherwise $matches is 0, and the $string is OK.

所以现在如果$ matches有1,你知道$ string包含坏字符。否则$ matches为0,$ string为OK。

#3


0  

To mixen things up a bit

混合了一点东西

<?
$input = "hello world 123!";
$digits = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");

if (ctype_alnum($input))
{
    if (ctype_lower(str_replace($digits, "", $input)))
    {
        // Input is only lowercase and digits
    }
}
?>

But regex is probably the way to go here! =)

但正则表达式可能是去这里的方式! =)