Best way to filter out certain characters.

Status
Not open for further replies.

Xenous

o shi
Nov 15, 2011
383
101
As the title says i'm wondering what would be the best way to filter out characters using php, characters like : ~!@#$%^&*()_+{}[]:";'<>,.?/ ect.
I had an idea for a method but it seems to have failed none to less the idea I had is
PHP:
$username = strip_tags(mysql_real_escape_string($_POST['username']));
$password = md5(strip_tags(mysql_real_escape_string($_POST['password'])));
$password2 = md5(strip_tags($_POST['password2']));
$email = strip_tags(mysql_real_escape_string($_POST['email']));
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
if (empty ($username)||empty($password)||empty($password2)||empty($email))
{
echo 'Please fill in all areas and try again';
}
else
{
$clean = '`,~,-,_,(,),*,&,^,%,$,#,@,!,;,:,.,/,?,<,>,{';
if ($username = $clean)
Care to elaborate on what I may have done wrong or the correct method for doing so, any help is appreciated as usual :)
 

Kryptos

prjRev.com
Jul 21, 2010
2,205
1,252
Should work.

PHP:
function validChars($str, $case)
    {
        switch($case)
        {
            case 'alpha':
                $case = '/[^a-zA-Z]/';
            break;
            
            case 'alphanum':
                $case = '/[^a-zA-Z0-9]/';
            break;
            
            case 'num':
                $case = '/[^0-9]/';
            break;
            
            case 'alphanumscore':
                $case = '/[^a-zA-Z0-9\ _]/';
            break;
        }
        
        return (preg_replace($case, null, $str) == $str ? true : false);
    }
 
$username = 'Kryptos}}%$5';
 
if(validChars($username, 'alphanum'))
{
    echo 'Username only contains numbers and letters!';
}
else
{
   echo 'Username contains special characters and/or underscores!';
}
 
Status
Not open for further replies.

Users who are viewing this thread

Top