Monday, 15 February 2010

php - Trying to remove everything but numbers, but regexes don't seem to work -



php - Trying to remove everything but numbers, but regexes don't seem to work -

i'm trying remove numbers variable in php. tried regexes, , quick google turns kinds of people telling me utilize regexes too, no regex seems work. i'm using preg_replace('/\d/', '', $amount);. tried kinds of different regexes, notably /\d/, /[\d]/, /^\d/, /[^\d]/, , /[^0-9]/, none of them work.

edit: found why didn't work! under impression preg_replace('/\d/', '', $amount); replace $amount, see have $new_amount = preg_replace('/\d/', '', $amount); , utilize $new_amount. stupid, know. anyway!

<?php $amount = '$42,3034534'; // remove chars $str = preg_replace('/[^0-9.,]/', '', $amount); // replace commas periods, because php doesn't commas decimals $str = preg_replace('/,/', '.', $str); // convert float , multiply 100, utilize floor() rid of fractions of cent $cents = floor(floatval($str) * 100); echo $cents; // or echo floor(floatval(preg_replace('/,/', '.', preg_replace('/[^0-9.,]/', '', $amount))) * 100); //output: 4230

also, stop saying "it doesn't work". how not working? result getting not correct?

php regex

No comments:

Post a Comment