不同preg_replace(^ 0 - 9)/或“\ D /”或“\ D /”?

时间:2021-07-21 00:10:42

What's the difference between regular expressions '/[^0-9]/' or '/\D/' or '/\d/'? And is it better to use single o double quotes?

有什么区别正则表达式“/[^ 0 - 9]/”或“\ D /”或“\ D /”?使用单o双引号更好吗?

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

谢谢! !

2 个解决方案

#1


5  

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

什么都可以,除了数字。它的别名(^ 0 - 9)。\ d意味着任何数量。这是[0 - 9]的别名(没有^)。“和”之间没有区别,因为你没有使用内部的“或”,并且在这个字符串中没有php变量。

#2


1  

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

将所有非数字替换为"

#1


5  

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

什么都可以,除了数字。它的别名(^ 0 - 9)。\ d意味着任何数量。这是[0 - 9]的别名(没有^)。“和”之间没有区别,因为你没有使用内部的“或”,并且在这个字符串中没有php变量。

#2


1  

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

将所有非数字替换为"