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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With