我使用短信API向手机发送确认码。
它的参数要求我将访客的电话号码格式设置为国际格式,例如+9912345678而不是012 345 678。
是否有一个PHP类(不需要Composer)可以为我完成这个任务(到目前为止在GG上找不到任何东西),考虑到我知道用户从先前网页提交的选择输入和文本输入中都知道他的国家和号码?
我使用短信API向手机发送确认码。
它的参数要求我将访客的电话号码格式设置为国际格式,例如+9912345678而不是012 345 678。
是否有一个PHP类(不需要Composer)可以为我完成这个任务(到目前为止在GG上找不到任何东西),考虑到我知道用户从先前网页提交的选择输入和文本输入中都知道他的国家和号码?
$originalNumber = '012345678';
$countryCode = '+99'; // Replace with known country code of user.
$internationalNumber = preg_replace('/^0/', $countryCode, $originalNumber);
echo $internationalNumber; // Will output: +9912345678
我之前使用过这个库(没有使用composer),效果不错:https://github.com/davideme/libphonenumber-for-PHP
你只需要在php中include
PhoneNumberUtil.php
,该文件会自动知道需要包含哪些内容。
你可以像这样格式化一个电话号码:
$swissNumberStr = "044 668 18 00";
$phoneUtil = PhoneNumberUtil::getInstance();
try {
$swissNumberProto = $phoneUtil->parseAndKeepRawInput($swissNumberStr, "CH");
var_dump($swissNumberProto);
} catch (NumberParseException $e) {
echo $e;
}
echo $phoneUtil->format($swissNumberProto, PhoneNumberFormat::INTERNATIONAL)
请查看demo.php
,以获取更多有关如何使用该库的示例。
根据@Huso的回答,我编写了以下函数来格式化和清理(删除破折号、点号和空格)电话号码:
function phonize($phoneNumber, $country) {
$countryCodes = array(
'ch' => '+41',
'de' => '+43',
'it' => '+39'
);
return preg_replace('/[^0-9+]/', '',
preg_replace('/^0/', $countryCodes[$country], $phoneNumber));
}
使用:
$phone = '022 123 43 65';
$country = 'ch';
$phone = phonize($phone, $country);
try {
$number = PhoneNumber::parse('+333');
}
catch (PhoneNumberParseException $e) {
// 'The string supplied is too short to be a phone number.'
}
格式化数字
$number = PhoneNumber::parse('+41446681800');
$number->format(PhoneNumberFormat::E164); // +41446681800
$number->format(PhoneNumberFormat::INTERNATIONAL); // +41 44 668 18 00
$number->format(PhoneNumberFormat::NATIONAL); // 044 668 18 00
$number->format(PhoneNumberFormat::RFC3966); // tel:+41-44-668-18-00
数字类型
PhoneNumber::parse('+336123456789')->getNumberType(); // PhoneNumberType::MOBILE
PhoneNumber::parse('+33123456789')->getNumberType(); // PhoneNumberType::FIXED_LINE
数字信息
$number = PhoneNumber::parse('+447123456789');
echo $number->getRegionCode(); // GB
echo $number->getCountryCode(); // 44
echo $number->getNationalNumber(); // 7123456789