Arcane Arcane - 2 months ago 7
JSON Question

How to correctly parse temperature from string in php?

I am trying to show temperature on my website. I have a forecast in json that I get from api and there is this field that I need to get the temperature from:


"fcttext_metric":"A mainly sunny sky. High near 30 ° C. Winds SE at 10 to 15 km/h."


I tried to parse only float numbers which works well, but it fails when there is more text behind it like in the case above. I tried to show only first 2 chars but when the temperature is negative it fails again. What can I do about this?

$str = 'A mainly sunny sky. High near 30 ° C. Winds SE at 10 to 15 km/h.';
$deg = filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT);
$res = substr($deg, 0, 2);
print_r($res);

Answer

I would use this regex. It should match integer values before ° (&deg) sign. Like 30 or -30

preg_match('/(\-?\d+)\s*°/', $str, $matches);
echo $matches[1];