php 将手机号码转为国际码(preg_replace + preg_quote)

本教学使用环境介绍
伺服器端:Ubuntu 18.04 LTS
资料库:Mariadb 10.1.34(Mysql)
语言版本:php 7.3
本机端:MacOS High Sierra

举例:台湾本地用户互打手机号码时,是 09XX123456,当与第三方串接需要转国际号时,需要变成 +8869XX123456,此时就可以使用此功能自由转换。

str_replace_national function

function str_replace_national($from, $to, $content) {
  $from = '/'.preg_quote($from, '/').'/';
  return preg_replace($from, $to, $content, 1);
}

使用

str_replace_national('0', '+886', $phone);

所以他只会取代第一个「0」,将它改为 +886

转回来一样原理

str_replace_first function

function str_replace_first($from, $to, $content) {
  $from = '/'.preg_quote($from, '/').'/';
  return preg_replace($from, $to, $content, 4);
}

使用

str_replace_first('+886', '0', $phone);

将 +886 取代为原本的「0」

Line ID:ianmac
QQ:1258554508

你可能感兴趣的:(ubuntu,php7,php,preg_replace)