How to remove initial (on the left) "+" or "0" from a telephone number string?

3.7k Views Asked by At

I need a regular expression in PHP to remove from a string of telephone numbers the + or the 0 at the beginning of a number.

I have this function to remove every not-number characters

ereg_replace("[^0-9]", "", $sPhoneNumber)

but I need something better, all these examples should be...

$sPhoneNumber = "+3999999999999"
$sPhoneNumber = "003999999999999"
$sPhoneNumber = "3999999999999"
$sPhoneNumber = "39 99999999999"
$sPhoneNumber = "+ 39 999 99999999"
$sPhoneNumber = "0039 99999999999"

... like this

$sPhoneNumber = "3999999999999"

any suggestions, thank you very much!

6

There are 6 best solutions below

0
Casimir et Hippolyte On BEST ANSWER

You can do this:

$result = preg_replace('~^[0\D]++|\D++~', '', $sPhoneNumber);
0
Schleis On

For removing the beginning + or 0, this should work

ereg_replace('^(\+|0)+?', '', $sPhoneNumber);

0
km6zla On

Just intval() afterwards to remove leading zeroes.

0
Jason McCreary On

As an alternative to regular expressions, you can use ltrim():

echo ltrim('003999999999999', '+0');

The second parameter is a character list string, in your case + and 0.

Note: This will not remove whitespace within the string, only the + and 0 from the beginning.

5
Tomalak On

Just extend your expression by a few alternative cases:

ereg_replace("^\+|^00|[^0-9]", "", $sPhoneNumber)

See http://ideone.com/fzj16b

0
wardpeet On

To be honest you don't need regex at all. Here is a clean solution as well.

// first remove spaces
// trim + and 0 characters at the beginning
ltrim(str_replace(' ', '', $sPhoneNumber), '+0');

this is my test code

<?php
$sPhoneNumber[0] = "+3999999999999";
$sPhoneNumber[1] = "003999999999999";
$sPhoneNumber[2] = "3999999999999";
$sPhoneNumber[3] = "39 99999999999";
$sPhoneNumber[4] = "+ 39 999 99999999";
$sPhoneNumber[5] = "0039 99999999999";

foreach ($sPhoneNumber as $number) {
    $outcome = ltrim(str_replace(' ', '', $number), '+0');
    echo $number . ':' . "\t" . $outcome . '(' . ($outcome === '3999999999999' ? 'true' : 'false') . ')' . "\n";
}