Allow only certain characters in a string

I was looking for a way to create a function to check if a string contains anything other than lowercase letters and numbers and if it returns false. I've searched the web, but all I can find are old methods that require using functions that are now deprecated in PHP5.

+2


source to share


3 answers


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

      



+2


source


Use a regular expression. Use preg_match () .

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

      



So, if it $matches

does 1

, you know what the $string

bad characters contain. Otherwise $matches

- 0

, and $string

- OK.

+1


source


To mix things up a little

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

0


source







All Articles