What's the difference between regular expressions '/[^0-9]/' or '/\D/' or '/\d/'? And is it better to use single o double quotes?
$number = '123asd456.789,123a4!"·$%&/()=/*-+<br>';
preg_replace('/\D/', '', $number) = 1234567891234
preg_replace('/\d/', '', $number) = asd.,a!"·$%&/()=/*-+
preg_replace('/[^0-9]+/', '', $number) = 1234567891234
Of course I did some testing and those were my results, I just want to undestand a bit more each regular expression. And which is better performance wise?
Thanks!!
\D
means anything, except number. It's alias of [^0-9]
.\d
means any number. It's alias of [0-9]
(without ^
).
And there is no difference between "
and '
, because you are not using inner "
or '
and there is no PHP-variables-like inside this string.
\d identical with [0-9] - digits in expression
\D identical with [^0-9] - NOT digits in expression
I use single quotes.
In your example:
preg_replace('/\D/', '', $number) - 1234567891234
will replace all NON digits with ''
preg_replace('/\d/', '', $number) = asd.,a!"·$%&/()=/*-+
will replace all digits with ''
preg_replace('/[^0-9]+/', '', $number) = 1234567891234
will replace all NON digits with ''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With