I have a get url input which I need to pass it into databse, but before doing that since I know that the user id would always be an integer number, I wanted to filter out everything but number in php. The follwoing code is what I came up with, does anyone know a better way than this? or is this the right way?
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
No.
The carat (^
) inside means NOT
. I.E. not a character between 0 to 9 inclusive. We need to remove that. Also, i
means that the regex is case insensitive; we don't need to worry about that because numbers don't have cases like other characters.
We need to select what want part we'd like to keep. Brackets are used for this. The second parameter needs to contain a reference to the part we'd like to replace the string with (before storing in $id
). So the whole function call would look like this:
$id = preg_replace('#([0-9]+)#', '\1', $_GET['id']);
+
just implies that there will be multiple digits.
You could then use is_int()
to ensure that the result of the function call is in fact an INT, because if the function found no digit it will just return the value of $_GET['id']
.
$id = preg_replace('#([0-9]+)#', '\1', $_GET['id']);
if(is_int($id))
{
//insert to DB
}