PHP: Use REGEX to Ensure that your received Variable is a Number CodeUnit 20 MAY 2011

It is a good idea to check that the variables your script is receiving are in fact of the correct type in terms of value passed. For example, when receiving some sort of record ID value, 99% of the time we are expecting a numeric value. A simple method to ensure that the variable to be processed is indeed numeric, is through the use of a simple REGEX statement applied using the preg_replace PHP function.

As an example, let’s process a user ID passed to us via a POST to our script:

$userid = (key_exists('user-id', $_POST)) ? preg_replace("@[^0-9-]@", '', $_POST['user-id']) : '-1';

What the above does is first check that the user-id is indeed present in the $_POST variable. If it isn’t, set our internal variable to -1. If it is present, replace all characters that don’t fall within the set of 0 to 9, excluding dashes, with a blank. This is assigned back to our variable for internal use.

So a simple check to guarantee that we’ve received either a positive (2) or negative (-2) number!


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.