Jump to content

Grabbing numbers only from a string, also eliminating decimals?


schapel

Recommended Posts

If anyone could help with this it would be greatly appreciated, I still haven't grasped all the intricacies of regex yet.

 

Here is my current function, to strip out any non-numeric characters from a string and return the cleaned up string.

 

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

 

I run into problems, however, when a number such as $5,000.00 comes into the function.  It returns 500000 instead of 5000 as desired.  I know what I need to do (only grab the string data from before the '.') just not how to do it exactly.

 

Thanks in advance.

Just in case anyone runs into this, I found a solution myself.  I'm not sure if it's the most efficient way to do it, but it works.  Just get rid of any decimals and decimal points first, then wipe out the non-numeric characters in a two step function.

 

function numbers_only($string) {
$decimals = preg_replace('/\.(\d{1,2})/', '', $string);
return preg_replace('/\D/', '', $decimals);
}

An alternative (without the need for dual preg statements):

 

function numbersOnly($input){
    $input = ($x = strstr($input, '.', true))? $x: $input; // PHP 5.3 required
    return preg_replace('#\D#', '', $input);
}

echo numbersOnly('$5,000.00');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.