View Full Version : Strip out commas and characters in a text box
Len Whistler
06-21-2007, 05:44 PM
I have a form that the user can enter a number in the text field and a calculation is then preformed with PHP when the form is submitted.
$amount = $_POST['amount'];
<input type="text" name="amount" size="20" value="">
Any way to strip out commas and any characters that may be entered. I would like an entry like $5000, 5000, 5,000 and $5,000 all to be passed on to the PHP script as 5000. The way it is now the php math script treats 5,000 as a 5 and $5000 as a 0.
Mwnciau
06-21-2007, 05:58 PM
preg_replace('#[^0-9]#', '', $_POST['text']);
$amount = preg_replace('#[^\d]#', '', $_POST['amount']);
That'll strip out all non digits with a regular expression :)
mlseim
06-21-2007, 06:06 PM
<?php
$amount = $_POST['amount'];
// replace anything that's NOT 0-9 with "null" (nothing)
$result=ereg_replace("[^0-9]","",$amount);
echo $result;
?>
Len Whistler
06-21-2007, 06:25 PM
Thanks for the fast replies.
Now another problem as appeared. $34.34 is calculated as 3434, anyway to let the decimals stay? Thanks
Mwnciau
06-21-2007, 06:28 PM
preg_replace('#[^0-9.]#', '', $_POST['text']);
This would probably be better:
preg_replace('#.*?([0-9]*(\.[0-9]*)?).*?#', '$1', $_POST['text']);
bcarl314
06-21-2007, 07:10 PM
You may also be interested in using is_numeric:
http://us.php.net/is_numeric
Len Whistler
06-21-2007, 08:07 PM
Thanks to all the replies. The code I used was the sample posted by Mwnciau.
preg_replace('#.*?([0-9]*(\.[0-9]*)?).*?#', '$1', $_POST['text']);
I tested it with all sorts of numbers such as 50.00, 50, $49.99, $50, 50.01 and they all were calculated as 50, or a penny difference for $49.99 and 50.01. And 5,000 and 5000 were both calculated as 5000. Thanks
I will look into is_numeric later on.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.