透過 PHP 為手機號碼添加國際|preg_replace|preg_quote|PHP|伊恩踩坑筆記

串接金流的時候可能會有一些電話格式的限制,例如一定要加「國際碼」,或是手機號碼不可含 0 等,只要寫個簡單的 function 就可以隨時替換了:

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

output

+886912333555

反之,將「國際碼」轉換為 0 來使用:

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

output

0912333555

ING Design 応設計
https://www.theingdesign.com/

--

--

Ian aka BerLin / 伊恩踩坑筆記

專門寫一些自己曾經踩過的坑,希望你沒踩過 / Web & BackEnd Developer • 台北 • theingdesign.com • IG: @ianakaberlin