简体   繁体   English

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

[英]php regex extract pattern but only the number inside it

I get data via a web service that I need to parse to find some value (sunshine duration) and this in php. 我通过Web服务获取数据,我需要对其进行解析以找到一些值(光照持续时间),并且该数据在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. 我已经可以找到所需的模式sunshine: 7.5 h ,但是我只需要找到的匹配项中有7.2 (实际上是一个数字)。 What would be the most straight forward way to do this in PHP? 用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)? 我可以在一个pre_match完成它,还是需要2 x pre_match (第二个在第一个匹配中)?

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

Simply add brackets to captured desired digits: 只需将括号添加到捕获的所需数字即可:

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

The performs your preg_match without PREG_OFFSET_CAPTURE : 无需PREG_OFFSET_CAPTURE执行您的preg_match

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

And in your matches[1] array you will found the desired result. 在您的matches[1]数组中,您将找到所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM