Replace phone prefix of multiple format using php

2019-09-26 01:31发布

I has an array :

    $phone_number = array ( 'phone' => '01219104579', 
    'phone' => '01219104579@abc.
    'phone' => '+8401219101219',
    'phone' => '01219104579/01219104479',
    'phone' => '841219104579@abc.com',
    'phone' => 'abcd01219104579@abc.com',
    'phone' => 'Hồ2101219104579@abc.com'
);

I need to replace all Phone NO prefix (0121 or 121) with new number prefix (072 or 72):

$phone_number = array ( 'phone' => '0729104579', 
'phone' => '0729104579@abc.com', 
'phone' => '+840729101219', 
'phone' => '0729104579/0729104479', 
'phone' => '84729104579@abc.com',
'phone' => 'abcd0729104579@abc.com',
'phone' => 'Hồ210729104579@abc.com' ); 

I tried to use PREG_REPLACE But i have problem with 8401219101219, number change to 84072910729. It should be 840729101219

How should I update all Phone NO using PHP

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-26 02:06

This code will do what you want. I'm presuming you actually want to replace 0121 or 121 with 072 or 72 since that's what your sample data shows. If you really want to replace 122, just change 121 to 122 in the regex below:

$phone_numbers = array ('01219104579', 
'01219104579@abc.com',
'+8401219101219',
'01219104579/01219104479',
'841219104579@abc.com'
);

foreach ($phone_numbers as $phone_number) {
    $new_numbers[] = preg_replace('/\b(\+?84?0?|0)121/', '${1}72', $phone_number);
}
print_r($new_numbers);

Output:

Array
(
    [0] => 0729104579
    [1] => 0729104579@abc.com
    [2] => +840729101219
    [3] => 0729104579/0729104479
    [4] => 84729104579@abc.com
)
查看更多
登录 后发表回答