我有以下整数
7
77
0
20在数组中。我使用它们来检查呼叫的发起地。
像730010123, 772930013, 20391938.这样的数字我需要做的是,我需要一种方法来检查数字是否以7或77开头。
有没有办法在PHP中做到这一点并避免上千条if语句?
我遇到的一个问题是,如果我检查号码是否以7开头,则以77开头的号码也会被呼叫。请注意,7个号码是移动号码,77个号码是共享费用号码,并且以任何方式不相等,所以我需要将它们分开。
发布于 2013-07-12 15:10:43
if (substr($str, 0, 1) == '7') ||{
if (substr($str, 0, 2) == '77'){
//starts with '77'
} else {
//starts with '7'
}
}发布于 2013-07-12 15:15:34
我用一个演示数组做了一个小例子,我希望你能使用它:
$array = array(
7 => 'Other',
70 => 'Fryslan!',
20 => 'New York',
21 => 'Dublin',
23 => 'Amsterdam',
);
$number = 70010123;
$place = null;
foreach($array as $possibleMatch => $value) {
if (preg_match('/^' . (string)$possibleMatch . '/', (string)$number))
$place = $value;
}
echo $place;在这种情况下,答案是"Fryslan“。你必须记住在这种情况下7也是匹配的?因此,在两个匹配的情况下,您可能需要添加一些度量系统。
发布于 2013-07-12 15:16:58
要做到这一点,一种方法是将接收到的“整数”作为数字处理为字符串。
要做到这一点,请执行以下操作:
$number = 772939913;
$filter = array (
'77' => 'type1',
'20' => 'type2',
'7' => 'type3',
'0' => 'type4');
$match = null;
foreach ($filter as $key => $val){
$comp = substr($number, 0, strlen($key));
if ($comp == $key){
$match = $key;
break;
}
}
if ($match !== null){
echo 'the type is: ' . $filter[$match];
//you can proceed with your task
}https://stackoverflow.com/questions/17609334
复制相似问题