拆分电话号码

时间:2012-02-29 18:50:49

标签: php arrays explode

获得以下代码:

// $partInfo has data filled in
// $partinfo['BusinessPhone'] = '-567-5675678-'
// $billdata *should* have data filled in
// $billdata['BillingInfo']['telephone'] = ''
$telephone = explode('-', $billdata['BillingInfo']['telephone']);
echo "<!-- Telephone: ". print_r($telephone, true)." -->";

产生

<!-- Telephone: Array
(
    [0] => 
)
-->    

// if billdata billinginfo telephone is blank
if(count($telephone)==0) {
  $telephone = explode('-', $partinfo['BusinessPhone']);
}
echo "<!-- Telephone2: ". print_r($partinfo['BusinessPhone'], true)." -->";

产生

<!-- Telephone2: -567-5675678- -->

但是...

echo "<!-- Telephone3: ". print_r($telephone, true)." -->";

产生

<!-- Telephone3: Array
(
    [0] => 
)
-->

我想,因为count($ telephone)返回1而不是空数组,那就是我出错的地方。最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

来自PHP documentation for explode返回值部分:

  

如果分隔符是空字符串(“”),则explode()将返回FALSE。 如果分隔符   包含一个未包含在字符串中的值,并使用负限制,然后使用   将返回空数组,否则将返回包含字符串的数组

所以发生的事情是,因为$billdata['BillingInfo']['telephone'] = ''包含一个空字符串,它不包含给定的分隔符,所以它返回一个包含给定字符串的数组。

你能做的是:

$telephone = false;
if ($billdata['BillingInfo']['telephone']) {
    $telephone = explode('-', $billdata['BillingInfo']['telephone']);
}

if (!$telephone) {
    $telephone = explode('-', $partinfo['BusinessPhone']);
}
相关问题