php:在数组中查找变量字符


php: find variable characters in an array

得到一个包含电话号码的变量,该号码前面有其国家前缀,该电话号码是动态的,可以是任何国家的任何电话号码。因此,我需要通过将变量中的某些字符(即电话号码前面的国家前缀)与DB中包含所有国家前缀的记录(国家前缀将被提取到数组中)进行匹配来获得电话号码的国家/地区。

样品:

$phoneVar = '4477809098888';  // uk - 44
$phoneVar = '15068094490';  // usa - 1
$phoneVar = '353669767954';  // ireland - 352
$phoneVar = '2348020098787';  // nigeria - 234

如果$phoneVar被分配了任何电话号码值,则需要能够从中获取国家/地区前缀。

类似这样的东西:

echo getCountryPrefix($phoneVar, $countries_prefix_array);

使用子可以很容易地实现这一点

// $countryPrefix = substr($phoneVar, 0, 3);

但各国的前缀长度并不相同。

很乐意得到帮助。

这样的东西会起作用。

它可能对您的代码不准确,但我相信您可以看到其中的逻辑。

function findCountryCode($number, $country_codes) {
    $country_codes = usort($country_codes, 'lsort');
    foreach ($country_codes as $key => $val) {
        if (substr($number, 0, strlen($val)) == $val)
            return $key;
    }
    return false;   
}

function lsort($a,$b) {
    return strlen($b)-strlen($a);
}

好吧,这是一个完美的状态机示例!

最简单的方法:

$prefixes = array('44' => 'UK', '1' => 'USA', '352' => 'IRELAND', '234' => 'NIGERIA');
preg_match('/^('.implode('|',array_keys($prefixes)).')/', $phoneVar, $matches);
echo $prefixes[$matches[0]];

您可能会发现这个模式很有用。

如果您维护前缀到国家/地区代码的映射,则编码是直接的。对前缀进行排序,从后面开始,因此在1之前尝试123。

您可以像以下代码一样执行此操作:

$phoneVar = '4477809098888';  // uk - 44
$county_list = array('uk' => 44, 'usa' => 1, 'ireland' => 352, 'nigeria' => 234);
foreach ($county_list as $key => $value)
{
    if (preg_match('/^'.$value.'/', $phoneVar))
    {
        echo "Country is: ".$key;
        echo "Country code: ".$value;
        break;
    }
}

输出

Country is: uk
Country code: 44

您可以使用preg_match():

$phoneVar = "abcdef";
$pattern = '/^44/';
preg_match($pattern, $phoneVar, $matches, PREG_OFFSET_CAPTURE, 3);
print_r("UK : ".$matches);

这可能意味着代码很长。但如果只有4个国家,那么这将符合你的目的。