我已经尝试过的东西...
<?
$dataArry = array (
"aab"=> array(
"mobile"=>'123456789',
"country"=>"Antigua and Barbuda",
"countryCode"=>"+1-268",
"pattern"=>"3#4",
"pattern2"=>"(xx)-xxxxxxx"
)
);
$data = $dataArry["aab"]["mobile"]; // number with leading 0...
if ($data[0] == "0" ) { //remove the leading 0 from number...
$data = substr($data, 1);
}
$pattern = $dataArry["aab"]["pattern2"];
echo preg_replace("([x]+)", $data, $pattern);
?>
我得到的结果为(123456789)-123456789
,但我想要结果
像(12)-3456789
实际上,我想根据该国家/地区将所有手机号码转换为数字格式,因此,我将一个国家/地区的模式保存在数据库中。因此,我可以稍后在需要显示它们时进行转换...
以前,我使用的是这段代码,但它的动态性并不强,因为格式可以像(12) 44 33 222, or 12 44 33 22
。所以我想到了保存(xx)xx xx xxx,xx xx xx xx xx这样的模式,并用数字替换所有x。模式中x的x数将始终相同。
<?
$match = "";
$dataArry = array(
"ind" => array(
"mobile" => '07505942189',
"country" => "india",
"countryCode" => "+91",
"pattern" => "3#3#4"
),
"us" => array(
"mobile" => '3784001234',
"country" => "US",
"countryCode" => "+1",
"pattern" => "3#3#4"
),
"aab" => array(
"mobile" => '4641234',
"country" => "Antigua and Barbuda",
"countryCode" => "+1-268",
"pattern" => "3#4"
),
"afg" => array(
"mobile" => '0201234567',
"country" => "Afghanistan",
"countryCode" => "+93",
"pattern" => "2#7"
)
);
$result .= $dataArry["afg"]["countryCode"] . " ";
$data = $dataArry["afg"]["mobile"]; // indian number with leading 0...
if ($data[0] == "0") { //remove the leading 0 from number...
$data = substr($data, 1);
}
$string = $dataArry["afg"]["pattern"]; // pattern code
$string = explode("#", $string); //making array of string pattern code.
foreach ($string as $vals) {
$match .= "(\d{" . $vals . "})";
}
//if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
if (preg_match("/" . $match . "/", $data, $matches)) {
for ($i = 1; $i < count($matches); $i++) {
if ($i == 1) {
$result .= "(";
}
$result .= $matches[$i];
if ($i == 1) {
$result .= ")";
}
if ($i < count($matches) - 1) {
$result .= "-";
}
}
echo $result;
}
//research https://en.wikipedia.org/wiki/List_of_mobile_telephone_prefixes_by_country
//research http://www.onesimcard.com/how-to-dial/
?>
答案 0 :(得分:2)
您可以使用preg_replace_callback来完成它:
$mobile = '123456789';
$pattern = '(xx)-xxxxxxx';
echo preg_replace_callback('/x+/', function ($match) use (&$mobile) {
$length = strlen($match[0]);
$replacement = substr($mobile, 0, $length);
$mobile = substr($mobile, $length);
return $replacement;
}, $pattern);