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.

Link to comment
Share on other sites

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);
}

Link to comment
Share on other sites

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');

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.