简体   繁体   中英

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

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!

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.

你可以这样做:

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

为了删除开头+0 ,这应该有效

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

之后只需intval()即可删除前导零。

Just extend your expression by a few alternative cases:

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

See http://ideone.com/fzj16b

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM