使用php

时间:2018-10-08 07:10:33

标签: php preg-replace phone-number

我有一个数组:

    $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'
);

我需要用新的号码前缀(072或72)替换所有电话号码前缀(0121或121):

$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' ); 

我尝试使用PREG_REPLACE 但是我对8401219101219有问题,请更改为84072910729。应为840729101219

如何使用PHP更新所有电话号码

1 个答案:

答案 0 :(得分:0)

此代码将执行您想要的操作。我假设您实际上想用0121121替换07272,因为这是示例数据所显示的。如果您确实要替换122,只需在下面的正则表达式中将121更改为122

$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);

输出:

Array
(
    [0] => 0729104579
    [1] => 0729104579@abc.com
    [2] => +840729101219
    [3] => 0729104579/0729104479
    [4] => 84729104579@abc.com
)