开发者

Regex: retrieve currency in JSON string

I'm using the Google calculator to retrieve converted prices, a sample output is this:

{lhs: "9000 Euros",rhs: "12 721.5 U.S. dollars",error: "",icc: true}

Now I cannot use json_decode for this JSON string, I've tried it but it doesn't work, so I'm using regex to retrieve the converted price in the rhs field.

I need to make the regex to be able to parse the number, not the currency name at all, just the number, however I have a problem with getting the price that includes a space in the field, my regex so far only gets 12, I cannot get the full thing 12 开发者_开发知识库721.5.

/rhs\: "(\d+|\s+)/i

How can I do this without including the price name? Note the response may/may not include space in the converted price and also a period.


If you only want to extract out the number part, then your regex could be:

 /[,{]\s*rhs\s*:\s*"([\d.\s]+)/

The [...] square brackets are the appropriate syntax for the alternatives here (any combination of decimals and spaces).

Edit: Missing decimals dot, and some more regex for verifying the "json" consistency.


The [...] should capture the space and the . and terminating before the space and the currency.

/rhs: "([\d .]+)\s/

EDIT: Adding php code which gets the data (in my environment)

$string = "{lhs: \"9000 Euros\",rhs: \"12 721.5 U.S. dollars\",error: \"\",icc: true}";

$pattern = '/rhs: "([\d .]+)\s/';
preg_match($pattern,$string,$matches);
print "<pre>"; var_dump($matches); print "</pre>";
echo $matches[1];


This regex: /rhs\: "(\d+|\s+)/i says (one or more decimal digits) or (one or more spaces). It doesn't allow for any combination of spaces of decimal digits.

$json = '{lhs: "9000 Euros",rhs: "12 721.5 U.S. dollars",error: "",icc: true}';

$matches = array();
preg_match('/"?rhs"?:\s*"((?:[\d ])*(?:\.\d+)?)/', $json, $matches);
$usd = floatval(str_replace(' ', '', $matches[1]));
echo $usd; // Outputs '12721.5'

This should work, and will continue to work if they ever make their JSON valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜