逗号将字符串划分为数组,但仅在PHP中的数字值



有一个像

的字符串
1,36,42,43,45,69,Standard,Executive,Premium

我想在数组中转换它,但仅需要数字值

Array
(
   [0] => 1
   [1] => 36
   [2] => 42
   [3] => 43
   [4] => 45
   [5] => 69
)

不是数组中的所有字符串值。

使用array_filterexplodeis_numeric功能简单且简短的解决方案:

$str = "1,36,42,43,45,69,Standard,Executive,Premium";
$numbers = array_filter(explode(",", $str), "is_numeric");
print_r($numbers);

输出:

Array
(
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
)

http://php.net/manual/en/function.is-numeric.php

print_r(array_filter(
    explode(',', '1,36,42,43,45,69,Standard,Executive,Premium'),
    'ctype_digit'
));
<?php
$array = array('1','36','42','43','45','69','Standard','Executive','Premium');
foreach($array as $value) if (is_integer($value)) $new_array[] = $value;
print_r($new_array);
?>

[编辑]哦,是的,我实际上更喜欢您的版本Romanperekhrest&amp;u_mulder:p

有一个外观附加片段:

请看一下演示:https://eval.in/593963

<?php
$c="1,36,42,43,45,69,Standard,Executive,Premium";
$arr=explode(",",$c);
foreach ($arr as $key => $value) {
    echo $value;
    if (!is_numeric($value)) { 
        unset($arr[$key]);
    }
}
print_r($arr);
?>

输出:

 Array
 (
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
    [6] => Standard
    [7] => Executive
    [8] => Premium
)
Array
(
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
)

tra this:

$string = "1,36,42,43,45,69,Standard,Executive,Premium";
print_r(array_filter(explode(',', $string), 'is_numeric'));

最新更新