0

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']);
Sokhrat Sikar
  • 175
  • 3
  • 4
  • 14

3 Answers3

5

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
}
Adam Lynch
  • 3,341
  • 5
  • 36
  • 66
  • what do you think of this: $id = filter_input(INPUT_GET, id, FILTER_SANITIZE_NUMBER_INT); – Sokhrat Sikar Feb 25 '12 at 22:20
  • 1
    It would return `1+234` from `1sada+sda2fdasddsa2sasd34a` whereas my code would only return `34`. `FILTER_SANITIZE_NUMBER_INT` removes all characters but digits and plus & minus signs and then sticks it all together whereas my code takes the first sequence of digits / block of digits in a row. With that function it would be easier to check if it failed though; you'd simply have `if(!$id){/*error*/}else{/*insert to DB*/}`. No need for `is_int()`. – Adam Lynch Feb 25 '12 at 23:11
0

You wouldnt need the i option if you are matching numbers. Your pattern will only match 1 numerical digit. I suggest something like

#[0-9]+# 

to get any length of numerical digits, ignoring anything else.

craig1231
  • 3,769
  • 4
  • 31
  • 34
0

Or this:

$id = preg_replace('/\D/', '', $_GET['id']);
davidethell
  • 11,708
  • 6
  • 43
  • 63