开发者

Only allowing certain characters in string

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 do开发者_开发问答es 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.


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


Use a regex. Use 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.


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! =)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜