Page 1 of 1

Checking for valid characters..

Posted: Thu Aug 21, 2003 5:43 pm
by Gen-ik
I was just wondering how you guys 'n gals go about checking for invalid characters in a string.

Basically i'm checking to make sure a username only contains a-z A-Z 0-9 and spaces... and it works using the following code but is there a better/cleaner/faster way of doing this :?:

Code: Select all

<?php
$c = Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9',' ');

$t = strtolower($username);

for($i=0; $i<strlen($t); $i++)
{
     $invalid = true;
     for($ii=0; $ii<count($c); $ii++)
     {
          if(stristr(substr($t,$i,1),$c[$i]))
          {
               $invalid = false;
          }
     }
}

if($invalid)
{
     $error = "your username contains invalid characters";
}
?>

Posted: Thu Aug 21, 2003 7:00 pm
by tsg
This is what I do and seems to work:

Code: Select all

if(eregi("[^a-z0-9]",$password)){ 
	echo("Your password contains a character that is not a letter or number. Please use only letters or numbers in your password");
	}

Posted: Thu Aug 21, 2003 7:09 pm
by McGruff
Apostrophes and dashes might be worth including for O'Reilly etc or double-barrelled surnames.

With all these new web accessibility laws, how long will it be before some bright hacker changes his name to <script> ?

Posted: Fri Aug 22, 2003 12:13 pm
by m3rajk
EEEEEEEWWWWWWWWWWW!!!!!!!!!

no posix. posix no good.

use perl

as i've been telling everyone about perl:
\w = [A-Za-z_]
\s = [\r\n\t ]


what you requested:
if(!(preg_match('/^[\w ]+$/', $variable))){ /* error stuff */}