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?
$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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With