モンモンブログ

技術的な話など

(php) いろんな形式の電話番号を統一形式に変換

いろんな形式の電話番号の文字列を、000-0000-0000 のような統一された形式に変換したい時ありますよね。こんな風に。

090 1234 5678 → 090-1234-5678
+81 90-1234-5678 → 090-1234-5678
+81 (90) 1234 5678 → 090-1234-5678

ユーザー入力の電話番号でDB検索かける時とかに必要んなります。

phpで関数を書きました。

function canonicalized_phonenumber ($phone) {
    // (, ) を取り除く
    $phone = preg_replace("/[()]/", ' ', trim($phone));
    // 国番号以外の番号をハイフンで繋ぐ
    if (preg_match("/^(\+[0-9]{2}[ -]+)?([0-9]+)[ -]+([0-9]+)[ -]+([0-9]+)$/", $phone, $m)) {
        if ('0' != $m[2][0]) $m[2] = '0'.$m[2];
        return "$m[2]-$m[3]-$m[4]";
    } else {
        return null;
    }
}

テスト。

assert(canonicalized_phonenumber('090-1234-5678') == '090-1234-5678');
assert(canonicalized_phonenumber('090 1234 5678') == '090-1234-5678');
assert(canonicalized_phonenumber('+81 90-1234-5678') == '090-1234-5678');
assert(canonicalized_phonenumber('+81 090-1234-5678') == '090-1234-5678');
assert(canonicalized_phonenumber('+81 (90) 1234 5678') == '090-1234-5678');
assert(canonicalized_phonenumber('0120 (123) 4567') == '0120-123-4567');
assert(canonicalized_phonenumber('  0120-123    4567 ') == '0120-123-4567');

いじょ。