开发者

How to filter any special characters

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

开发者_如何学JAVA$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?


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

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


 $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);


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

$new_str = preg_replace("/[^a-zA-Z0-9]/", "", $str);


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜