Reputation: 3796
I get data via a web service that I need to parse to find some value (sunshine duration) and this in php. My idea would be to do it with regex.
I can already find the desired pattern sunshine: 7.5 h
, but I only need the 7.2
(as a number actually) out of the found match. What would be the most straight forward way to do this in PHP?
Can I do it in one pre_match
, or will I need to to 2 x pre_match
(second one on the match of the first one)?
My code:
//test data
$testInputs = array (
0 => "blabla sunshine: 7 h blabla",
1 => "blabla sunshine: 7.5 h blabla",
2 => "blabla sunshine: 0.5 h blabla"
);
//pattern
$pattern = '/sunshine: [\d]*.?[\d]*/';
//test
foreach($testInputs as $testInput)
{
preg_match($pattern, $testInput, $matches, PREG_OFFSET_CAPTURE);
print($testInput);
print_r($matches);
print("<br>");
}
output
sunshine: 7 h Array ( [0] => Array ( [0] => sunshine: 7 [1] => 1 ) )
sunshine: 7.5 h Array ( [0] => Array ( [0] => sunshine: 7.5 [1] => 1 ) )
sunshine: 0.5 h Array ( [0] => Array ( [0] => sunshine: 0.5 [1] => 1 ) )
Upvotes: 0
Views: 29
Reputation: 11689
Simply add brackets to captured desired digits:
'/sunshine: ([\d]*.?[\d]*)/'
The performs your preg_match
without PREG_OFFSET_CAPTURE
:
preg_match($pattern, $testInput, $matches);
And in your matches[1]
array you will found the desired result.
Upvotes: 1