I am trying to figure out how to strip special characters from user input in a PHP search form before the SQL SELECT query is run.
I have a PHP search form that submits user input to a select query > mysql 5 > Linux. The select query looks at one column for a LIKE match and brings back the results to a results page. The column in the database has no special characters – just alpha numeric values.
My database field value would look like this 33345678DEP
If the user entered 333-456*78DEP , how would I strip the special characters?
I read about REGEX – looks like it might be the answer but I do not know how to implement it.
MY PHP Code that preforms the search is as follows:
if (isset($_GET['InventoryByVendorForm'])) {
$colname_InventoryByVendorResults = $_GET['InventoryByVendorForm'];
}
mysql_select_db($database_ic3, $ic3);
$query_InventoryByVendorResults = sprintf("SELECT icCombinedSupplier_wrk.icMaster_icmKEY, icCombinedSupplier_wrk.icsSupplierID, icCombinedSupplier_wrk.icsPartNum, icCombinedSupplier_wrk.icsQuantityOnHand, icCombinedSupplier_wrk.icsCost, icCombinedSupplier_wrk.icsCore, icCombinedSupplier_wrk.icsLastInventoryUpdate, icMaster.icmLineCode, icAttributes.`icaPartslink#` AS icaPartslink FROM icMaster INNER JOIN (icCombinedSupplier_wrk INNER JOIN icAttributes ON icCombinedSupplier_wrk.icMaster_icmKEY = icAttributes.icMaster_icmKEY) ON icMaster.icmKEY = icCombinedSupplier_wrk.icMaster_icmKEY WHERE `icCombinedSupplier_wrk`.`icMaster_icmKEY` Like %s ORDER BY icMaster_icmKEY ASC", GetSQLValueString("%" . $colname_InventoryByVendorResults . "%", "text"));
My best guess would that I would need to implement the use of REGEX [[alnum]] around the statement:
$colname_InventoryByVendorResults = $_GET['InventoryByVendorForm']
How could I accomplish stripping all non-alpha /numeric characters from the user input in the search box?
preg_replace is the right tool to do this:
There are shortcuts for alphanumeric character sets, but this way it is quite intuitively understandable.
The “^” negeates the selection, so any character not being alphanumeric will be replaced by an empty string.
Have a nice day,
Stefan