PHP - Zahlen formatieren

Aus Wikizone
Wechseln zu: Navigation, Suche

You should be able to do it with the following regex:

[^0-9+]

In preg_replace():

$nn = preg_replace('/[^0-9+]/', , $string);

Telefonnummer

Entferne alles außer Zahlen und +

Your current regex also keeps a forward-slash, so to keep that functionality:

$nn = preg_replace('/[^0-9\/+]/', , $string);

Sample code with output:

<?php
$string = '+27 (15) 234-2634';
$nn = preg_replace("/[^0-9+]/", "", $string );
echo $nn . "\n";
?>

Results in:

+27152342634

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 just preg_replace():

$nn = preg_replace("/[^0-9+]/", "", $string);
if (substr_count($nn, '+') > 1) {
    $firstPlus = strpos($nn, '+') + 1;
    $nn = substr($nn, 0, $firstPlus) . str_replace('+', '', substr($nn, $firstPlus));
}

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 second preg_replace() here too, but to remove only a + symbol it would be overkill.

Here's a codepad entry for the sample.