PHP - 从多维数组中删除字符

时间:2015-03-27 14:25:58

标签: php arrays multidimensional-array

我有一个这样的数组:

array(2) {
  ["test"]=>
  string(4) "test"
  ["recipients"]=>
  array(1) {
    ["recipient_0"]=>
    array(1) {
      ["phone-number"]=>
      string(12) "068-842-7893"
    },
["recipient_1"]=>
array(1) {
  ["phone-number"]=>
  string(12) "068-842-7893"
},
["recipient_2"]=>
array(1) {
  ["phone-number"]=>
  string(12) "068-842-7893"
}
  }....
}

我需要从电话号码中删除所有非数字字符。我怎么能这样做?

3 个答案:

答案 0 :(得分:2)

请参阅preg_replace功能:

$number = preg_replace('~[^\d]~', '', $array['recipients']['recipient_0']['phone-number']);

对于更多收件人(根据以下OP评论):

foreach ($array['recipients'] as $r) {
    echo preg_replace('~[^\d]~', '', $r['phone-number']);
}

答案 1 :(得分:1)

因为您没有提供代码。这可能会对你有所帮助。

这将删除字符串中的所有非数字字符。

preg_replace("/[^0-9]/", "", $string);

根据你的代码:

$number_of_recipients = count($array["recipients"]);
for($i=0; $i<$number_of_recipients; $i++){
    echo preg_replace("/[^0-9]/", "", $array["recipients"]["recipient_$i"]["phone-number"]);
}

答案 2 :(得分:0)

这样的事情应该这样做。

foreach ($arr['recipients'] as & $recipient) {
    $recipient['phone-number'] = preg_replace('/[^\d]/', null, $recipient['phone-number']);
}

您也可以遍历数组,将函数应用于每个值:

array_walk($arr['recipients'], function ( & $value) {
    $value['phone-number'] = preg_replace('/[^\d]/', null, $value['phone-number']);
});