如何用给定的数字替换模式中的x?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用给定的数字替换模式中的x?相关的知识,希望对你有一定的参考价值。
我还试过了......
<?
$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这样的模式,并用数字替换所有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/
?>
答案
你可以使用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);
以上是关于如何用给定的数字替换模式中的x?的主要内容,如果未能解决你的问题,请参考以下文章
如何用 Android 数据绑定替换 androidx.fragment.app.FragmentContainerView 中的片段