PHP数组删除字符,仅保留数字

3

寻找能够从数组中删除字符并仅显示数字的代码。

array( 
    1=>123456 hello; / &, 
    2=>128767 ^% * ! ajsdb, 
    3=>765678 </ hello echo., 
); 

我想从数组中删除以下内容。
hello; / &
^% * ! ajsdb
</ hello echo.

并希望保持如上所述。
array( 
    1=>123456, 
    2=>128767, 
    3=>765678, 
); 

感谢您的来信,祝您一切顺利。
敬礼。

你需要一个正则表达式来完成这个任务。 - Faizan Ali
8
这是否是作业 - 0b10011
这些是有效的数组元素吗? - Aditya M P
8个回答

14

您想使用 preg_replace 将所有非数字字符替换为 ''。

$arr = array(
    1 => "1234 perr & *",
    2 => "3456 hsdsd 3434"
);

foreach($arr as &$item) {
    $item = preg_replace('/\D/', '', $item);
}

var_dump($arr);

结果为

array(2) { [1]=> string(4) "1234" [2]=> &string(8) "34563434" } 

2

编写一个for循环语句来获取数组的值,尝试执行以下操作:

    foreach($arr as $value){
        $cleansedstring = remove_non_numeric($value);
        echo $cleansedstring;
    }


function remove_non_numeric($string) {
return preg_replace('/\D/', '', $string)
}

2
<?php

// Set array
$array = array( 
    1 => "123456 hello; / &", 
    2 => "128767 ^% * ! ajsdb", 
    3 => "765678 </ hello echo.",
);

// Loop through $array
foreach($array as $key => $item){
    // Set $array[$key] to value of $item with non-numeric values removed
    // (Setting $item will not change $array, so $array[$key] is set instead)
    $array[$key] = preg_replace('/[^0-9]+/', '', $item);
}

// Check results
print_r($array);
?>

1
function number_only($str){
    $slength = strlen($str);
    $returnVal = null;
    for($i=0;$i<$slength;$i++){
        if(is_numeric($str[$i])){
            $returnVal .=$str[$i];
        }
    }
    return $returnVal;
}

0

你应该使用 preg_replace 函数,其中的模式应为 [0-9]+


0
我建议您查看intval方法(http://php.net/manual/en/function.intval.php)和foreach循环(http://php.net/manual/en/control-structures.foreach.php)。通过这两个函数的组合,您将能够清除所有非数字字符的元素。

0

像这样

$values = array(
    1=>"123456 hello; / &",
    2=>"128767 ^% * ! ajsdb",
    3=>"765678 </ hello echo",
);

$number_values = array();
foreach($values as $value) {
    $pieces = explode(' ', $value);
    $numbers = array_filter($pieces, function($value) {
        return is_numeric($value);
    });

    if(count($numbers) > 0)
    {
        $number_values[] = current($numbers);
    }
}

print_r($number_values);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接