I want to replace all non-numeric characters in a string except a +.
I’ve tried this question, but it’s not working…
Here is what I have at the moment:
$nn = preg_replace("/([^0-9\/+]+)/", "", $string );
It works 100%, except for removing the + in any way…
EDIT
My input will always contain only 1 +, and should there be more, they should be removed.
Basically, if a user enters a phone number as (015) 234-2634 it should be returned as +27152342634 (South African Country Code – I add the +27 at a later stage) But if +27 (15) 234-2634 is entered, +27152342634 should be returned.
You should be able to do it with the following regex:
In
preg_replace():Your current regex also keeps a forward-slash, so to keep that functionality:
Sample code with output:
Results in:
UPDATE (keep only first matching
+)Per your latest question-update, you also only want to keep the first
+symbol found. To do this, since there may not be a “rule” regarding the location of the first symbol (such as “it has to be the first character in the string), I would suggest using additional methods other than justpreg_replace():This code will perform the original
preg_replace()as normal and then, if there are more than 1+symbols in the result, it will get a sub-string of the result up to the first+, then perform a string-replacement to replace all remaining+symbols. You could always use a secondpreg_replace()here too, but to remove only a+symbol it would be overkill.Here’s a codepad entry for the sample.