// 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;
});
giggsey/libphonenumber-for-php (Composer)libphonenumber-jscomposer 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