Remove the currency format using regular expression - php

I am trying to find a piece of regex to remove a currency format.
I have two types of currency values. One is in USD format like 1,000.00 and other is in EUR like 1.000,00. I need to save the value in to db by removing both comma and dot like 1000.00
For example if the user enter the value in USD like 2,222.65, it need to replace to 2222.65,
if the user enter the value in EUR like 2.222,65 it also need to replace to 2222.65,

Instead of complex regex, use NumberFormatter::parse available for PHP 5 >= 5.3.0, PECL intl >= 1.0.0.
// German format
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."<br>\n";
// USD format
$fmt = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
$num = "9,876,543.012";
echo $fmt->parse($num)."<br>\n";
OUTPUT:
1234567.891
9876543.012

One soultion to match what separator in use, and change it to the one you prefere
<?php
/* split input in 3 parts: integer, separator, decimals */
if(preg_match('#^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$#', $input, $matches))
{
/* clean integer and append decimals with your own separator */
$number = ((int) preg_replace('#[^0-9]+#', '', $matches['integer']) . '.' . $matches['decimals']
}
else
{
$number = (int) preg_replace('#[^0-9]+#', '', $input);
}
?>
Notice: I prefer to have my regexp in # insted of /, as i ofen use / inside my regexp,
if ypu prefer / you can use /[^0-9]+/ and /^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$/

This assumes that they all have decimals, but it is the cleanest.
$str = "2,222.65";
$clean = preg_replace('/[^\d]/', '', $str);
$clean = substr($clean, 0,-2) . "." . substr($clean,-2);

Related

Laravel - How Convert Thousand Comma to Decimal Number

i have input form currency with format like this 1,000.00
and i want to save in database in decimal format like 1000.00
how to change it in controller, when save it it will automatically change to decimal format?
$num = '3,500.20';
$formattedNum = number_format($num, 3, '', '');
echo $formattedNum;
the code above convert to 3000 not 3500.20
you can use str_replace of php to get you result:
<?php
$num = '3,500.20';
$formattedNum = str_replace(',', '', $num);
echo $formattedNum;
?>
str_replace funcation replace your ',' with '' a blank value,
To read more about str_replace you can read here
You can just remove comma with str_replace(',', '', $num) for example.
But better to get correct value right from your input.
Input format shouldn't affect actual input value which is 3500.20, that doesn't look as good practice.
Also number_format is not for converting string to numbers, on the contrary it makes pretty string from number(integer/float).
You can try str_replace for the desired result:-
$number = '3,500.20';
$number = str_replace(',', '', $number);
echo $number;
Output
3500.20

Using PHP preg_replace match result in a math operation?

I want to find a number in a string, add one to it, and replace it. These don't work:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".("$1"+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("$1")+1)."str", $original);
Where 'str' is a very identifiable string, each side of the number (and does not contain numbers).
I realise I can do this in more than one line of code quite easily but it seems like this should be possible.
Using a callback function allows you to cast a match to number and increment, e.g.:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);
Solely using str_replace you can get the number from the string, add one to it, and the replace the old number with the new one :
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;

Get only ordinal suffix with NumberFormatter

Is it possible to get only the suffix of a number with the NumberFormatter class in PHP.
For example:
$nf = new NumberFormatter( 'en', NumberFormatter::ORDINAL );
$out = $nf->format( 10000 );
echo $out . "\n";
Will result in: '10,000th'
I would just like: 'th', i.e. the suffix.
I don't believe that is possible with NumberFormatter, the best you could do would be to grab the last two characters:
echo substr($out, -2);
Otherwise skip NumberFormatter and find the suffix a different way

How to replace all characters except a numeral (200, 200.45 etc.) from a string in php?

I have few strings where i need to extract only the prices in php (which will obviously be numerals).
The use cases are follows:
1) Rs. 23,459.45 desired output = 23459.45
2)Our best price 23,459.45 desired output = 23459.45
etc.
I gave the above use cases to give an idea that the preceding characters could be anything.
Please help!
How about:
$arr = array(
'Rs. 23,459.45 ',
'Our best price 23,459.45 ',
);
foreach($arr as $string) {
$string = preg_replace('/^.*?(\d+),?(\d{3})(\.\d{2})?.*$/', "$1$2$3", $string);
echo $string,"\n";
}
output:
23459.45
23459.45
It's:
$result = preg_replace('/[^0-9.]/', '', $string);
-but note, this will not validate numbers or provide valid result in common case since string could contain something like 'foo . bar,baz . price 20.5 with .6 discount' - end result will be not a valid number. So code above answers the question about "how to replace", but does not fit validating a number (and you've not mentioned if that is your goal).
About validating a number - such question will be ambiguous because it's not obvious how to convert ..20.5.6 (which will be result for string above). But if you need only to check that, use is_numeric() on $result, like this:
$string = 'foo . bar,baz . price 20.5 with .6 discount';
$result = preg_replace('/[^0-9.]/', '', $string);
$result = is_numeric($result)?(float)$result:null;
You can use this to validate the above strings. When this function valiadates Rs. , it will return two dots, so I used ltrim to remove the first dot.
<?php
//$s = "Rs. 23,459.45";
$s= "Our best price 23,459.45";
echo $result = ltrim(preg_replace("/[^0-9.]+/", "", $s),'.');
?>
http://codepad.org/cyH5OWyE

Parse a number but keep negative's

I am trying to un-format a number to it's original form but keep whether or not it is negative. Someone on stack overflow led me to this code that work's very nicely but it does not keep the negative.
Could anyone help me get a better fix on this?
EDIT - For USD Currency/normal numbers
Example:
1,234 = 1234
-1,234 = -1234
1,234.00 = 1234
1,234.56 = 1234.56
function numberUnformat($number)
{
$cleanString = preg_replace('/([^0-9\.,])/i', '', $number);
$onlyNumbersString = preg_replace('/([^0-9])/i', '', $number);
$separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;
$stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
$removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot);
return (float) str_replace(',', '.', $removedThousendSeparator);
}
In case you have the ICU extension (which is bundled in PHP 5.3) available, try this:
$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->parse('-1,234.56');
Change your regular expression to match the negative numbers, too:
$cleanString = preg_replace('/([^\-0-9\.,])/i', '', $number);
Test cases:
echo numberUnformat('1,234')."\n";
echo numberUnformat('-1,234')."\n";
echo numberUnformat('1,234.00')."\n";
echo numberUnformat('1,234.56 ')."\n";
Output:
1234
-1234
1234
1234.56
Demo!
If you want to remove any extraneous minus signs in the middle of the string, too:
$cleanString = preg_replace('/[^0-9.,-]|(?<=.)-/', '', $number);
$onlyNumbersString = preg_replace('/[^0-9-]|(?<=.)-/', '', $number);
Note that you don't need the parentheses, backslash, or /i in your original.
I would actually add some parameters to the function to allow specification of grouping and decimal separators (and possibly allow ability to cast to float or decimal and go to a solution like this:
function number_unformat($num_string, $group_sep = ',', $dec_sep = '.', $cast_to_type = true) {
if (substr_count($num_string, $dec_sep) > 1) {
// input was invalid
throw new Exception('Inavlid string: `' . $num_string . '` passed to function. Too many decimal separators.');
}
// remove grouping separator
$string = str_replace($group_sep, '', $num_string);
if (true === $cast_to_type) {
// change any decimal separators to periods before casting
$string = str_replace($dec_sep, '.', $string, $count);
if ($count === 1) {
return (float)$string;
} else {
return (int)$string;
}
} else {
return $string;
}
}
Note that there is no need at all to use regular expression here.
A fairly quick (though imperfect) fix would be to change the first two lines of the function:
$cleanString = preg_replace('/([^-0-9\.,])/i', '', $number);
$onlyNumbersString = preg_replace('/([^-0-9])/i', '', $number);
Though this will cause a problem if you have a number like 2-434.43.
One could muck with the regular expressions to keep the negative, but to me it's simpler to do the following at the end:
$absvalue = (float) str_replace(',', '.', $removedThousendSeparator);
if ($number[0] == '-') {
$absvalue = $absvalue * -1.0;
}
return $absvalue;
I might have a syntax error in there, my PHP is rusty, but the idea is just to check and see if the input string starts with a negative sign, and if it does, multiply the result by negative 1.

Categories