67

How can I modify this existing preg_replace to only allow numbers?

function __cleanData($c) 
{
    return preg_replace("/[^A-Za-z0-9]/", "",$c);
}
Ryan
  • 14,392
  • 8
  • 62
  • 102

4 Answers4

214

I think you're saying you want to remove all non-numeric characters. If so, \D means "anything that isn't a digit":

preg_replace('/\D/', '', $c)
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
43

Try this:

return preg_replace("/[^0-9]/", "",$c);
qbert220
  • 11,220
  • 4
  • 31
  • 31
  • 1
    In case you want to keep the dot for decimal numbers, it would be like this: ```return preg_replace("/[^0-9.]/", "", $c);``` – Pierre Jul 24 '22 at 05:41
22

This should do what you want:

preg_replace("/[^0-9]/", "",$c);
random_user_name
  • 25,694
  • 7
  • 76
  • 115
oezi
  • 51,017
  • 10
  • 98
  • 115
1

In my case, I want to keep number and '.' only

return preg_replace("/[^0-9.]/", "",$c);