schapel Posted January 15, 2010 Share Posted January 15, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/188635-grabbing-numbers-only-from-a-string-also-eliminating-decimals/ Share on other sites More sharing options...
schapel Posted January 16, 2010 Author Share Posted January 16, 2010 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); } Quote Link to comment https://forums.phpfreaks.com/topic/188635-grabbing-numbers-only-from-a-string-also-eliminating-decimals/#findComment-995894 Share on other sites More sharing options...
nrg_alpha Posted January 16, 2010 Share Posted January 16, 2010 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'); Quote Link to comment https://forums.phpfreaks.com/topic/188635-grabbing-numbers-only-from-a-string-also-eliminating-decimals/#findComment-995913 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.