NumberFormatter parse Euro's with comma as decimal splitter - php

I've a big headache over this. Why isn't this code working?
<?php
setlocale(LC_MONETARY, 'nl');
$fmt = new NumberFormatter( 'nl', NumberFormatter::CURRENCY );
$num = "€2,50";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>
I've tried this on both a Windows machine and at http://phpfiddle.org/. The expected outcome is We have 2.50 in EUR.
The dutch locale is as following:
>>> localeconv()
=> [
"decimal_point" => ",",
"thousands_sep" => ".",
"int_curr_symbol" => "EUR",
"currency_symbol" => b"€",
"mon_decimal_point" => ",",
"mon_thousands_sep" => ".",
"positive_sign" => "",
"negative_sign" => "-",
"int_frac_digits" => 2,
"frac_digits" => 2,
"p_cs_precedes" => 1,
"p_sep_by_space" => 1,
"n_cs_precedes" => 1,
"n_sep_by_space" => 1,
"p_sign_posn" => 4,
"n_sign_posn" => 4,
"grouping" => [
3,
],
"mon_grouping" => [
3,
],
]

The currency parser is super strange and expects a non breaking space UTF-8 sign between the currency symbol and the number.
This example works fine for me:
<?php
setlocale(LC_MONETARY, 'nl');
$fmt = new NumberFormatter( 'nl', NumberFormatter::CURRENCY );
$num = "€\xc2\xa02,50";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>
\xc2\xa0 is the code for that breaking space.

Related

Json encode Unicode Symbol in PHP array

Given the following array
$locationIcon = array(
'face' => 'FontAwesome',
'code' => '\uf015',
'size' => 75,
'color' => 'gray',
);
which is encoded via json_encode, I would like to have this output:
{
face: 'FontAwesome',
code: '\uf015',
size: 75,
color: 'gray'
}
but instead I get these results:
Version 1
json_encode($array)
=>
"icon":{"face":"FontAwesome","code":"\\uf2bd","size":40,"color":"gray"}
Version 2 as seen here
json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
=>
"icon" {"face":"FontAwesome","code":"\\uf2bd","size":40,"color":"gray"} (same)
Version 3 (add an escape char)
$locationIcon = array(
'face' => 'FontAwesome',
'code' => sprintf('%cuf2bd', 27),
'size' => 100,
'color' => 'gray',
);
json_encode($array)
=>
"icon" {"face":"FontAwesome","code":"\u001buf233","size":40,"color":"gray"}
Any ideas what I am doing wrong?
Well, you have written the string "backslash u f zero one five", and JSON-encoding that preserves it exactly with that meaning. There's no sane way around that. Write the actual character you want, not "\uf015". Since this particular character can be slightly awkward to write, write it in some alternative notation, like raw UTF-8 bytes:
$locationIcon = [
'code' => "\xEF\x80\x95", // U+F015
...
];
echo json_encode($locationIcon); // {"code": "\uf015", ...}

How to lowercase string with special characters?

I have this array in PHP:
$weekdays = array(
"mandag" => 1,
"tirsdag" => 2,
"onsdag" => 3,
"torsdag" => 4,
"fredag" => 5,
"lørdag" => 6,
"søndag" => 7);
The function gets the day with random formats like all uppercase or one letter uppercase, I'm doing an strtolower from the variable and then comparing it with the array.
The problem comes here, when I do strtolower on the var with a special character like this one ø from søndag and lørdag, it doesn't recognize the string. How can I change the string to strtolower without modifying the special character?
Try mb_strtolower
$weekdays = array("Mandag" => 1, "Tirsdag" => 2, "Onsdag" => 3, "Torsdag" => 4, "Fredag" => 5, "Lørdag" => 6, "Søndag" => 7);
$weekdays = array_combine(
array_map('mb_strtolower', array_keys($weekdays)),
$weekdays
);
var_dump($weekdays);
...or if you want to check a specific item in the array you can simply run mb_strtolower($item, 'UTF-8') on it.
$happyDay = "SøndAg";
echo $happyDay . ' -> ' . mb_strtolower($happyDay, 'UTF-8');

PHP MongoDB find with multiple "AND" conditions?

After hours of experimentations and readings, I cannot find a solution to this problem:
I want to do a MongoDB->find($query) with multiple AND conditions.
For instance, say I want id = 5 and a < 6 and a > 2 and b > 10 and b < 20
I was expecting $query to be:
$query = array("id" => 5,
"a" => array('$gt' => 2,
'$lt' => 6),
"b" => array('$gt' => 10,
'$lt' => 20))
But this returns empty results with my DB
I tried various syntaxes such as:
$query = array("id" => 5,
array( "a" => array('$gt' => 2,
'$lt' => 6),
"b" => array('$gt' => 10,
'$lt' => 20)))
But this fails too.
Also tried with "$AND" variants, no luck.
Is it possible to "mix" several AND conditions in PHP-MongoDB find() requests?
I've just tested this using MongoDB PHP driver v1.6.11 (PHP-5.5.9). The test data are as below
db.collection.insert({id:5, a:4, b:15})
db.collection.insert({id:9, a:4, b:15})
db.collection.insert({id:5, a:4, b:20})
Using PHP code snippet:
$condition = array(
'$and' => array(
array(
"id" => 5,
"a" => array('$gt' => 2, '$lt' => 6),
"b" => array('$gt' => 10, '$lt' => 20)
)
)
);
$docs = $coll->find($condition);
foreach( $docs as $o=> $doc) {
echo json_encode($doc);
}
The above returns only the first document sample. This indicates that $and should work as expected. I've also tested without $and, i.e. :
$condition = array(
"id" => 5,
"a" => array('$gt' => 2, '$lt' => 6),
"b" => array('$gt' => 10, '$lt' => 20)
);
Which also works the same. Try checking your dataset, whether there is a document matching your criteria.
This issue is closed: bad value types in the DB (string instead of float/double). Works as expected when updating to correct types in DB.

how to make json string by using php array?

This is the target jason string:
{"dpid": 272, "priority": 10, "match": {"nw_src": "192.168.1.1", "nw_dst": "192.168.1.2", "nw_proto": 1, "eth_type": 0x0800}, "actions":[{"type": "DROP"}]}
This is the php array that i made:
$rule = array(
"dpid" => 272,
"priority" => 10,
"match" => {"nw_src": "$_POST['src']", "nw_dst": "$_POST['dst']", "nw_proto": 1, "eth_type": 0x0800},
"actions"=> [{"type": "DROP"}],
);
i am trying to turn this array into the json string above, using:
$data_string=json_encode( $rule );
but it doesnt work :(
i know the array is really non-sense, i am really new to php. Could somebody help me?
Your array should be:
$rule = array(
"dpid" => 272,
"priority" => 10,
"match" => array(
"nw_src" => $_POST['src'],
"nw_dst" => $_POST['dst'],
"nw_proto" => 1,
"eth_type" => 0x0800
),
"actions"=> array(array("type" => "DROP")),
);
After that json_encode function will do all the work for you:
$data_string = json_encode($rule);

get integer / float from string in PHP

I ran into an issue with a data feed I need to import where for some reason the feed producer has decided to provide data that should clearly be either INT or FLOAT as strings-- like this:
$CASES_SOLD = "THREE";
$CASES_STOCKED = "FOUR";
Is there a way in PHP to interpret the text string as the actual integer?
EDIT: I should be more clear-- I need to have the $cases_sold etc. as an integer-- so I can then manipulate them as digits, store in database as INT, etc.
Use an associative array, for example:
$map = array("ONE" => 1, "TWO" => 2, "THREE" => 3, "FOUR" => 4);
$CASES_SOLD = $map["THREE"]; // 3
If you are only interested by "converting" one to nine, you may use the following code:
$convert = array('one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6,
'seven' => 7,
'eight' => 8,
'nine' => 9
);
echo $convert[strtolower($CASES_SOLD)]; // will display 3
If you only need the base 10 numerals, just make a map
$numberMap = array(
'ONE' => 1
, 'TWO' => 2
, 'THREE' => 3
// etc..
);
$number = $numberMap[$CASES_SOLD];
// $number == 3'
If you need something more complex, like interpreting Four Thousand Two Hundred Fifty Eight into 4258 then you'll need to roll up your sleeves and look at this related question.
Impress your fellow programmers by handling this in a totally obtuse way:
<?php
$text = 'four';
if(ereg("[[.$text.]]", "0123456789", $m)) {
$value = (int) $m[0];
echo $value;
}
?>
You need a list of numbers in english and then replace to string, but, you should play with 'thousand' and 'million' clause where must check if after string 'thousend-three' and remove integer from string.
You should play with this function and try change if-else and add some functionality for good conversion:
I'm writing now a simple code for basic, but you know others what should change, play!
Look at million, thousand and string AND, it should be change if no in string like '1345'. Than replace with str_replace each of them separaterly and join them to integer.
function conv($string)
{
$conv = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
'FOUR' => 4,
'FIVE' => 5,
'SIX' => 6,
'SEVEN' => 7,
'EIGHT' => 8,
'NINE' => 9,
'TEN' => 10,
'ELEVEN' => 11,
'TWELVE' => 12,
'THIRTEEN' => 13,
'FOURTEEN' => 14,
'FIFTEEN' => 15,
'SIXTEEN' => 16,
'SEVENTEEN' => 17,
'EIGHTEEN' => 18,
'NINETEEN' => 19,
'TWENTY' => 20,
'THIRTY' => 30,
'FORTY' => 40,
'FIFTY' => 50,
'SIXTY' => 60,
'SEVENTY' => 70,
'EIGTHY' => 80,
'NINETY' => 90,
'HUNDRED' => 00,
'AND' => '',
'THOUSAND' => 000
'MILLION' => 000000,
);
if (stristr('-', $string))
{
$val = explode('-', $string);
#hardcode some programming logic for checkers if thousands, should if trim zero or not, check if another values
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
else
{
foreach ($conv as $conv_k => $conv_v)
{
$string[] = str_replace($conv_k, $conv_v, $string);
}
return join($string);
}
}
Basically what you want is to write a parser for the formal grammar that represents written numbers (up to some finite upper bound). Depending on how high you need to go, the parser could be as trivial as
$numbers = ('zero', 'one', 'two', 'three');
$input = 'TWO';
$result = array_search(strtolower($input), $numbers);
...or as involved as a full-blown parser generated by a tool as ANTLR. Since you probably only need to process relatively small numbers, the most practical solution might be to manually hand-code a small parser. You can take a look here for the ready-made grammar and implement it in PHP.
This is similar to Converting words to numbers in PHP
PHP doesn't have built in conversion functionality. You'd have to build your own logic based on switch statements or otherwise.
Or use an existing library like:
http://www.phpclasses.org/package/7082-PHP-Convert-a-string-of-English-words-to-numbers.html

Categories