Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace all non-digit characters except + at start of string

Tags:

regex

replace

php

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!

like image 266
krixon Avatar asked Dec 14 '25 15:12

krixon


1 Answers

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)
like image 54
stema Avatar answered Dec 16 '25 08:12

stema



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!