After having checked everywhere in vain I decided to post this problem here. I am Working on an online shop where the client needs to show automatically a "free shipping label" for all items that cost 100€ or more. I did make a function that worked with plain numbers (80€), but when the price is in this format (2.453,90€) it doesn´t.
I would really appreciate your help if you could shed some light on this issue. Thanks in advance
just remove dot and put dot instead of comma for php to recognize this as a number:
$plainNumber = floor(str_replace(",",".",str_replace(".","","2.453,90")));
if($plainNumber >= 100)
{
//do intended stuff
}
You could use regular expressions to transforms formatted numbers in raw numbers.
$number = preg_replace('/\./', '', $number);
$number = preg_replace('/,/', '.', $number);
You could also store raw numbers instead of formatted numbers.
Stringified data types are a not uncommon beginner error. You should always handle numbers as native numbers and only convert to string when printing them.
When you use numbers, good old comparison operators become useful.
Related
to use approved google merchant, I need to send them the price in this format:
2,00 EUR must been written as 2.00 ou 2.
100 000,00 EUR must be written 100000 or 100000.00, and not 100,000.00, 100,000 or +100,000.
Negatives values, like -20,14 EUR, must be written -20.14.
what I've got in my database actually is written like 100.000,00€
so to replace it, I've use:
$total_price = substr(str_replace(",", ".", str_replace(".", "", $order->info['total'])),0, -6);
Which is quite bad in my opinion. any thoughts on this?
You can use NumberFormatter::parseCurrency to parse a string into a double and a currency using the current formatter.
well regular expressions would help you keep things tidy, but you will still need to remove the dot you have lying around in there, and replacing the comma with a dot afterwards. once you have that, you can use
$str = preg_replace('/[^0-9.]+/', '', $str);
to eliminate any currency labeling you saved. Note to future you: when developing software for multi-currency transactions, you should separate values from currencies. this way you can keep a decimal value in the db and keep the type of currency in tnother and not bother with this all together.
have fun! let me know if you need anything else
I have the following problem. I need to validate and possibly extract currency from a value that I have received. The trouble starts with the fact that the value can be received in any encoding. Additionally to make things worse I can receive a lot of different values that should be considered correct. Let me give an example
$ 123,123,233.00
123,123.99
123.123.123,99
123.123.123 $
All of these are correct.
What I've tried is adding three arrays:
1. Chars (",","."," ")
2. Digits(0-9)
3. Currency Signs($,€...)
Trouble started when the data came in UTF-8 and I can no longer perform search digit by digit on the value I've received as in UTF-8 Currency signs are multibyte.
Question is what to do !?
I've tried the following thing.
Search for a currency sign. Then replace it with nothing. For some unknown reason PHP only replaces the second byte of the multibyte representation of the currency sign and there is a mysterious sign in the string that fails the whole check.
Any ideas are welcomed.
Datelligent idea may actually be a good simple solution: you could replace every non numerical character except the ones useful for puntuaction, with this regex \D*(?!\d{1,2}[\D$]):
$price=preg_replace('\D*(?!\d{1,2}[\D$])', '', $price);
It would transform 1233,234 234.23 into 1233234234.23.
Careful though, stuff like 123,2 34,234 would end up 123,2 34234. It does assume that punctuation followed by three or more digits isn't relevant, doesn't account for potential typos, will delete the currency symbol, etc... but it may be relevant to the scope of your issue.
Try this:
$price=$_POST['price'];
$price=preg_replace('/[^0-9]/', '', $price);
This way PHP will remove all characters and give you a string containing only numbers, which for handling prices is perfect.
If decimals are needed then modify the RegEx to get them:
$price=preg_replace('[0-9]+(\.[0-9][0-9]?)?', '', $price);
I have a "price" field in a mysql database, which contains the price of a product in arabic or persian numbers.
Example of number: ۱۲۳۴۵۶۷۸۹۰ //1234567890
I cannot figure out how to format this so that it is formatted in a user-friendly way.
By that I mean, grouped by thousands or something similiar.
This would be ideal: ۱ ۲۳۴ ۵۶۷ ۸۹۰
number_format in php is what I would have used on latin numbers.
Is there any function which I don't know about, to make this possible?
If not, ideas of how to create one is appreciated.
Thanks
You could use a regex like this:
([۱۲۳۴۵۶۷۸۹۰])(?=(?:[۱۲۳۴۵۶۷۸۹۰]{3})+$)
Search and replace with \1, on the string ۱۲۳۴۵۶۷۸۹۰ would give you ۱,۲۳۴,۵۶۷,۸۹۰ (using , instead of space since SO trims them off. But using space in the replace instead will work just as well).
I would have to agree with the suggestion in the comments though, store the data using the numeric types available and convert them on input/output.
If you can store numbers in your database instead of strings (or convert to ascii numbers), then standard currency formatting with group-separators can be done with php5-intl functions. You just need ISO locale and currency codes:
$nf = new \NumberFormatter('fa_IR', \NumberFormatter::CURRENCY);
echo $nf->formatCurrency(1234.1234, 'IRR');
۱٬۲۳۴ ﷼
Otherwise, #rvalvik's answer is good.
See http://php.net/manual/en/class.numberformatter.php
More elegantly written than #rvalvik's regex pattern, you can add a comma after a character that is followed by 3, 6, 9, etc. characters.
Code: (Demo)
$str = '۱۲۳۴۵۶۷۸۹۰';
var_export(
preg_replace(
'~.\K(?=(?:.{3})+$)~u',
",",
$str
)
);
Output:
'۱,۲۳۴,۵۶۷,۸۹۰'
Here is similar answer to a related question.
I have an input for users where they are supposed to enter their phone number. The problem is that some people write their phone number with hyphens and spaces in them. I want to put the input trough a filter to remove such things and store only digits in my database.
I figured that I could do some str_replace() for the whitespaces and special chars.
However I think that a better approach would be to pick out just the digits instead of removing everything else. I think that I have heard the term "whitelisting" about this.
Could you please point me in the direction of solving this in PHP?
Example: I want the input "0333 452-123-4" to result in "03334521234"
Thanks!
This is a non-trivial problem because there are lots of colloquialisms and regional differences. Please refer to What is the best way for converting phone numbers into international format (E.164) using Java? It's Java but the same rules apply.
I would say that unless you need something more fully-featured, keep it simple. Create a list of valid regular expressions and check the input against each until you find a match.
If you want it really simple, simply remove non-digits:
$phone = preg_replace('![^\d]+!', '', $phone);
By the way, just picking out the digits is, by definition, the same as removing everything else. If you mean something different you may want to rephrase that.
$number = filter_var(str_replace(array("+","-"), '', $number), FILTER_SANITIZE_NUMBER_INT);
Filter_Var removes everything but pluses and minuses, and str_replace gets rid of those.
or you could use preg_replace
$number = preg_replace('/[^0-9]/', '', $number);
You could do it two ways. Iterate through each index in the string, and run is_numeric() on it, or you could use a regular expression on the string.
On the client side I do recommand using some formating that you design when creating a form. This is good for zip or telephone fields. Take a look at this jquery plugin for a reference. It will much easy later on the server side.
I am trying to find a piece of regex to match a currency value.
I would like to match only numbers and 1 decimal point ie
Allowed
10
100
100.00
Not Allowed
Alpha Characters
100,00
+/- 100
I have search and tried quite a few without any luck.
Hope you can advise
if (preg_match('/^[0-9]+(?:\.[0-9]+)?$/', $subject))
{
# Successful match
}
else
{
# Match attempt failed
}
Side note : If you want to restrict how many decimal places you want, you can do something like this :
/^[0-9]+(?:\.[0-9]{1,3})?$/im
So
100.000
will match, whereas
100.0001
wont.
If you need any further help, post a comment.
PS If you can, use the number formatter posted above. Native functions are always better (and faster), otherwise this solution will serve you well.
How about this
if (preg_match('/^\d+(\.\d{2})?$/', $subject))
{
// correct currency format
} else {
//invalid currency format
}
You might want to consider other alternatives to using a regex.
For example, there's the NumberFormatter class, which provides flexible number and currency parsing and formatting, with build in internationalisation support.
It's built into PHP 5.3 and later, and is available as an extension on earlier versions of PHP 5.
Try this regular expression:
^(?:[1-9]\d+|\d)(?:\.\d\d)?$