views:

118

answers:

3

Hi,

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.

So how do we do it in PHP5?

A: 

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

sshow
+1  A: 

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.

yjerem
Remember that this function can return false as well, so you should check it using the type comparison operator, `===`: $matches = preg_match('/[^a-z0-9]/', $string); if($matches === 0) { // code here when it matches }
Nathan Kleyn
+1  A: 
function check_input( $text ) {
  if( preg_match( "/[^a-z0-9]/", $text ) ) {
    return false;
  }
  else {
    return true;
  }
}
Devin Ceartas