preg_replace all non-digit characters except + at

2019-05-11 04:30发布

问题:

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

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.

Thanks!

回答1:

Try this

/(?<!^)\D|^[^+\d]/

\D is the same than [^\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)


回答2:

Use positive lookbehind.

preg_replace('/(?<=\d)[^\d]+/', '', $string)