Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diference between preg_replace '/[^0-9]/' or '/\D/' or '/\d/'?

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!!

like image 902
joseagaleanoc Avatar asked Oct 16 '14 14:10

joseagaleanoc


2 Answers

\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.

like image 93
Justinas Avatar answered Oct 06 '22 20:10

Justinas


\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 ''

like image 36
Jevgenijs Vaikulis Avatar answered Oct 06 '22 20:10

Jevgenijs Vaikulis