A function that returns only numbers?

function get_only_numbers($string){
    $getonly = str_split("0123456789");
    $string = str_split($string);
    foreach($string as $i => $c){
        if(!in_array($c, $getonly))
            unset($string[$i]);
    }
    return implode("", $string);
}

echo get_only_numbers("U$ 499,50"); // prints 49950

This function should only return numbers from a string. Is this function encoded correctly?

+3
source share
3 answers

I think one call to preg_replace can do this:

preg_replace('/\D+/', '', 'U$ 499,50'); // returns "49950"
+4
source

See is_numeric for further optimization of your function so that you don't have array matching.

+3
source

Correctly? He does what he should ... but I prefer regular expressions:

function get_only_numbers($string){
    return preg_replace("/[^0-9]/", "", $string);
}
+2
source

All Articles