Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter any special characters

Tags:

php

If i have input text in form like this

<form action="add.php" method="post">
<input type="text" name="txt" id="txt">
<input type="submit" name="submit" value="Submit">
</form>

and the add.php code is as following

$sql= "insert into mytable set myname='$txt'";
executeupdate($sql);

My question how to filter any text input from any special characters i just want it only Aa-Zz-1234567890 (letters and numbers) only.

Here is my try but i'm not sure will it really filter all special characters or can pass any

i've added in add.php the following code

$cleared = strip_tags($txt);
$sql= "insert into mytable set myname='$cleared'";
executeupdate($sql);  // this should clear the name before insert

Any suggestions else or better way?

like image 318
Reham Fahmy Avatar asked Aug 14 '11 14:08

Reham Fahmy


4 Answers

$txt = preg_replace('/[^a-zA-Z0-9]/', '', $txt);

Also, there's nothing "special" about characters outside of the A-Z, 0-9 range.

like image 187
deceze Avatar answered Oct 04 '22 04:10

deceze


 $whiteSpace = '\s';  //if you dnt even want to allow white-space set it to ''
$pattern = '/[^a-zA-Z0-9'  . $whiteSpace . ']/u';
 $cleared = preg_replace($pattern, '', (string) $txt);
like image 30
Mr Coder Avatar answered Oct 04 '22 04:10

Mr Coder


If you just want to remove all non alpha-numeric characters:

$new_str = preg_replace("/[^a-zA-Z0-9]/", "", $str);
like image 35
Dogbert Avatar answered Oct 04 '22 03:10

Dogbert


I'd try the following:

<?php
    //Replace non-alphanumerics with an "" ie nothing
    $cleared = preg_replace("/[^a-z0-9]/i", "", $txt);
?>

Hope this works out for you!

like image 38
karllindmark Avatar answered Oct 04 '22 04:10

karllindmark