68

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

function __cleanData($c) 
{
    return preg_replace("/[^A-Za-z0-9]/", "",$c);
}

4 Answers 4

218

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)
0
46

Try this:

return preg_replace("/[^0-9]/", "",$c);
1
  • 1
    In case you want to keep the dot for decimal numbers, it would be like this: return preg_replace("/[^0-9.]/", "", $c);
    – Pierre
    Commented Jul 24, 2022 at 5:41
22

This should do what you want:

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.