Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function that returns only numbers?

Tags:

php

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 is supposed to return only the numbers from a string. Has this function been coded properly?

like image 401
user1091856 Avatar asked Aug 31 '26 17:08

user1091856


2 Answers

I think a single call to preg_replace can do that as well:

preg_replace('/\D+/', '', 'U$ 499,50'); // returns "49950"
like image 113
anubhava Avatar answered Sep 03 '26 11:09

anubhava


See is_numeric to further optimize your function so that you don't need the array comparison.

like image 35
Shomz Avatar answered Sep 03 '26 11:09

Shomz