I got decimal problem while I parsing my command. 12.90 has been parsed wrongly:
// My command
$cmd = 'CREATE product price:12.90, name: "Create me"';
// My parser
preg_match_all('/\w+|".*?"|(?!\s)\W/', $cmd, $list);
Output:
Array
(
[0] => CREATE
[1] => product
[2] => price
[3] => :
[4] => 12 // << problem starts here
[5] => .
[6] => 90
[7] => ,
[8] => name
[9] => :
[10] => "Create me"
)
I am looking for this output:
Array
(
[0] => CREATE
[1] => product
[2] => price
[3] => :
[4] => 12.90 // supposed
[5] => ,
[6] => name
[7] => :
[8] => "Create me"
)
So, how can I solve this problem?
Edit: (the better solution)
Guys, I accepted Jesse’s answer according to my question. But I realized it is not good enough for my complex commands. It’s better, because it works with both decimals like 12.90 and alias names like p.price. So just look at my example and parser below for it. I hope this help someone.
// My command
$cmd = 'GET `order` -o, product -p
LIST o.user_id, o.product_id, p.name, p.price
REL o.order_id = 3 AND p.price > 12.90';
// My complex command:
preg_match_all('/[0-9_\.]+|\w+|".*?"|`.*?`|\'.*?\'|!=|<=|>=|(?!\s)\W/', $cmd, $list);
// Output:
Array
(
[0] => Array
(
[0] => GET
[1] => `order`
[2] => -
[3] => o
[4] => ,
[5] => product
[6] => -
[7] => p
[8] => LIST
[9] => o
[10] => .
[11] => user_id
[12] => ,
[13] => o
[14] => .
[15] => product_id
[16] => ,
[17] => p
[18] => .
[19] => name
[20] => ,
[21] => p
[22] => .
[23] => price
[24] => REL
[25] => o
[26] => .
[27] => order_id
[28] => =
[29] => 3
[30] => AND
[31] => p
[32] => .
[33] => price
[34] => >
[35] => 12.90
)
)
\wclass does not include the.so the “quick” fix is to add it as follows:Do you have any other requirements regarding where the period is allowed? (ie only matching when it is between numbers?). If so, you may need to make the matching more specialized.
The biggest thing thing that jumps out at me is if the period would be used as delimiter for some other aspect of your parser. If the RE that you gave is your entire parser you are probably ok.