萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 手機號碼與市話驗證正則:台/陸制式、可選國碼、統一驗證介面

台灣手機號碼

// 09xx-xxx-xxx 或 09xxxxxxxx
const PHONE_TW_MOBILE = '/^09\d{2}-?\d{3}-?\d{3}$/';

台灣市話(含區碼)

// 02-23456789, 03-1234567, 037-123456, 04-12345678 等
const PHONE_TW_LANDLINE = '/^0(?:[2-8]|37)-?\d{6,8}$/';

中國大陸手機號碼

// 13/14/15/16/17/18/19 開頭,11 位
const PHONE_CN_MOBILE = '/^1[3-9]\d{9}$/';

// 含國碼 +86
const PHONE_CN_MOBILE_WITH_CC = '/^(\+?86)?1[3-9]\d{9}$/';

中國大陸市話

// 區碼 3-4 碼 + 號碼 7-8 碼,可選 - 分隔
const PHONE_CN_LANDLINE = '/^(?:0\d{2,3}-?)?[1-9]\d{6,7}$/';

統一驗證介面

<?php
class PhoneValidator {
    private static array $patterns = [
        'TW_MOBILE'     => '/^09\d{2}-?\d{3}-?\d{3}$/',
        'TW_LANDLINE'   => '/^0(?:[2-8]|37)-?\d{6,8}$/',
        'CN_MOBILE'     => '/^1[3-9]\d{9}$/',
        'CN_MOBILE_CC'  => '/^(\+?86)?1[3-9]\d{9}$/',
        'CN_LANDLINE'   => '/^(?:0\d{2,3}-?)?[1-9]\d{6,7}$/',
    ];

    public static function validate(string $phone, string $type = 'TW_MOBILE'): bool {
        $pattern = self::$patterns[$type] ?? self::$patterns['TW_MOBILE'];
        return (bool)preg_match($pattern, $phone);
    }

    public static function normalize(string $phone): string {
        // 移除所有非數字、+ 號
        return preg_replace('/[^\d+]/', '', $phone);
    }

    public static function format(string $phone, string $type = 'TW_MOBILE'): string {
        $clean = self::normalize($phone);
        return match ($type) {
            'TW_MOBILE' => preg_replace('/^09(\d{2})(\d{3})(\d{3})$/', '09$1-$2-$3', $clean),
            'TW_LANDLINE' => $clean, // 視區碼長度動態格式化
            'CN_MOBILE' => preg_replace('/^(\+?86)?1(\d{10})$/', '+86 1$2', $clean),
            default => $clean,
        };
    }
}

// 使用
var_dump(PhoneValidator::validate('0912-345-678', 'TW_MOBILE')); // true
var_dump(PhoneValidator::validate('13800138000', 'CN_MOBILE'));  // true
echo PhoneValidator::format('0912345678', 'TW_MOBILE'); // 0912-345-678

前端輸入遮罩

<input type="tel" name="phone" inputmode="tel"
       placeholder="0912-345-678"
       pattern="09\d{2}-?\d{3}-?\d{3}"
       title="格式:09XX-XXX-XXX">

// JS 即時格式化
input.addEventListener('input', e => {
    let v = e.target.value.replace(/\D/g, '');
    if (v.startsWith('09') && v.length > 3) {
        v = v.slice(0,4) + '-' + v.slice(4,7) + '-' + v.slice(7,10);
    }
    e.target.value = v;
});

國際化庫推薦

  • libphonenumber (Google):最完整、支援所有國家格式、解析、驗證、格式化
  • PHP 移植:giggsey/libphonenumber-for-php (Composer)
  • 前端:libphonenumber-js
composer require giggsey/libphonenumber-for-php

use libphonenumber\PhoneNumberUtil;
$util = PhoneNumberUtil::getInstance();
$num = $util->parse('0912345678', 'TW');
echo $util->format($num, PhoneNumberFormat::NATIONAL); // 0912-345-678
echo $util->isValidNumber($num); // true

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved