Re: Removing commas from number

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




On Sun, May 6, 2007 10:33 am, Todd Cary wrote:
> Thanks to the suggestions, I use number_format($my_number, 2) to
> format the
> number in an edit field.  Now I need to reenter it into MySQL.  How
> should I use
> preg_replace to remove the commas?
>
> This removes the commas *and* the decimal point:
>
> preg_replace('/\D/', '', $str)
>
> In reviewing patterns, I cannot find the purpose of the "/" character
> in the above.

//to JUST replace the comma:
$str = str_replace(',', $str);

The '/' is not part of the pattern, but a delimiter to set pattern
separate from modifiers.
http://php.net/pcre

You could also do something not unlike:

$str = preg_replace("|[^0-9\\.-]|', '', $str);

Here I chose '|' for the delimiter instead of '/' because I felt like it.

You can choose different things in different circumstances being easier.

If '/' is actually IN the pattern, it's clunky as a delimiter because
you then have to escape it in the pattern.

By forcing the data to ONLY contain 0-9 . and - you pretty much
drastically increase the odds that any other stray typo won't get
through.

You could also consider testing with 'is_numeric' to rule out goofy
things like:
5.2.2
which is probably not valid input for what you are doing, but does
pass the pattern I've listed...

Or, you could try a more specific pattern:

|-?[0-9]*(\\.[0-9]{2})?|

which I *think* means:

A leading -, maybe
Any number of 0-9 digits
A period *and* 2 more digits, or nothing

This still doesn't guarantee valid input, though, as '' passes this
pattern :-v

The trick is to be as precise as you can about what you accept,
without rejecting anything that is valid.

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some indie artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux