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

11次阅读

共计 622 个字符,预计需要花费 2 分钟才能阅读完成。

本教学使用环境介绍伺服器端: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:ianmacQQ:1258554508

正文完
 0