PHP 正则表达式提取模式,但只有其中的数字


php regex extract pattern but only the number inside it

我通过一个网络服务获取数据,我需要解析这些数据以找到一些值(日照持续时间),这是在 php 中。我的想法是用正则表达式来做。

我已经可以在sunshine: 7.5 h找到所需的模式,但我只需要找到的匹配项中的7.2(实际上是数字)。在 PHP 中执行此操作最直接的方法是什么?

我可以在一个pre_match中做到这一点,还是我需要 2 x pre_match(第一个匹配的第二个)?

我的代码:

//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>");
 }

输出

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 ) )

只需为捕获的所需数字添加括号:

'/sunshine: (['d]*.?['d]*)/'

无需PREG_OFFSET_CAPTURE即可执行您的preg_match

preg_match($pattern, $testInput, $matches);

在您的matches[1]阵列中,您将找到所需的结果。