preg_replace 除 + 字符串开头的所有非数字字符 [英] preg_replace all non-digit characters except + at start of string
问题描述
假设输入字符串 +123-321+123 345
,使用 PHP 的正则表达式函数,我想删除所有非数字 ([^\d]
) 字符, 除了开头的 +
字符.+
可能存在也可能不存在,因此给定字符串 123-321+123 345
结果应该是相同的(123321123345
).
Assuming the input string +123-321+123 345
, using PHP's regex functions I would like to remove all non-digit ([^\d]
) characters, except the +
character at the start. The +
may or may not be present, so given the string 123-321+123 345
the result should be the same (123321123345
).
目前的解决方法是检查 +
,然后运行 preg_replace('/[^\d]+/', '', $string)
,但我确信必须有一个纯正则表达式来解决这个问题.
Currently the workaround in place is to check for the +
, then run preg_replace('/[^\d]+/', '', $string)
, but I'm sure there must be a pure regex solution to this problem.
谢谢!
推荐答案
试试这个
/(?<!^)\D|^[^+\d]/
\D
与 [^\d]
(?<!^)
是一个负向后视,确保在非数字之前没有字符串的开头.
(?<!^)
is a negative lookbehind that ensures that there is not the start of the string before the not a digit.
此表达式将匹配所有不是字符串开头的非数字.
This expression will match all non digits that are not a the start of the string.
preg_replace('/(?<!^)\D|^[^+\d]/', '', $string)
这篇关于preg_replace 除 + 字符串开头的所有非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!