1

Basically what this needs to do is only accept a price value, that can only be 40 or 39.95 or 100.09 or 4 etc, if the user enters anything other than a digit into the field it comes back with an error.

My question: how can I change it so that if the user inputs a dollar sign in the input field that it just gets stripped out rather than returning an error in that particular case?


if (ereg_replace('/^\d+(\.\d{2})?$/', $_POST['itemAmt'])) {
    echo '<h1>The original cost of the item: $' . $_POST['itemAmt'] . ' </h1>';
} else {
    echo '<h1 style="color:red; font-weight:900;">The price value was not numeric, try again :) </h1><br>';
}
hakre
  • 193,403
  • 52
  • 435
  • 836
amanda89
  • 17
  • 1
  • 2
  • 3
  • All the ereg_* functions are deprecated. Check the docs http://php.net/ereg_replace – Mike B Jan 06 '13 at 20:19
  • 2
    Never change data, make validators, that validate user's input, and return return if user inputed wrong data... – Glavić Jan 06 '13 at 20:20

3 Answers3

6
$itemAmt = str_replace(array('$', '%'), '', $_POST['itemAmt']);
zerkms
  • 249,484
  • 69
  • 436
  • 539
2
preg_replace('#[^0-9\.]+#','',$_POST['itemAmt']);
MDEV
  • 10,730
  • 2
  • 33
  • 49
0

possible way

if ( preg_match( '/^(\d+(?:\.\d+)?)[\$%]?$/', $_POST['itemAmt'] ) ) {
    $validprice = preg_replace( '/^(\d+(?:\.\d+)?)[\$%]?$/', '\1', $_POST['itemAmt'] );
} else {
    // invalid input
}
bukart
  • 4,906
  • 2
  • 21
  • 40