PHP preg replace only allow numbers

2019-03-08 10:29发布

问题:

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

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

回答1:

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)


回答2:

Try this:

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


回答3:

This should do what you want:

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


回答4:

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api