0

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 ) )
1
  • what if someone entered 7,5 instead of 7.5 ? Commented Mar 19, 2016 at 19:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Woaw that simple, how could I miss that. Thanks @fusion3k, works perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.