Checking for valid characters..

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Gen-ik
DevNet Resident
Posts: 1059
Joined: Mon Aug 12, 2002 7:08 pm
Location: London. UK.

Checking for valid characters..

Post 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";
}
?>
tsg
Forum Contributor
Posts: 142
Joined: Sun Jan 12, 2003 9:22 pm
Location: SE, Alabama
Contact:

Post 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");
	}
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post 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> ?
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post 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 */}
Post Reply