Preg_replace all non-digit characters except + at the beginning of the line

Assuming an input string +123-321+123 345

using PHP regex functions, I would like to remove all non-digit characters ( [^\d]

) except for the character +

at the beginning. +

may or may not be present, so given the string, the 123-321+123 345

result should be the same ( 123321123345

).

The current workaround is to check for +

then launch preg_replace('/[^\d]+/', '', $string)

, but I'm sure there should be a purely regular solution for this problem.

Thank!

+3


source to share


2 answers


try it

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

      

\D

coincides with [^\d]



(?<!^)

is a negative lookbehind, which ensures that the beginning of the line must not be before a digit.

This expression will match all non-digits that are not the beginning of a line.

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

      

+5


source


Use positive lookbehind.



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

      

0


source







All Articles