2017-08-08 46 views
1

我有,例如:最好的方式获得分钟从几小时?

$hours = "10:11 - 13:34"; 

如何为GET分钟,这个字符串的最好方法?我最想有他们的阵中,例如

$results = array(11, 34); 

然后还可以是:

$hours = "7:10 - 22:00"; 
$hours = "07:55-14:15"; 
$hours = "07:55 -14:15"; 

等等

我可以:

$expl = explode('-', trim($hours)); 

然后用“:”爆炸,但也许是更好的方法?

+0

做它regexp-way使用https://regex101.com/构建(研究)正则表达式代码生成。 – vatavale

回答

2

我觉得preg_match_all是你所需要的

$a = "7:10 - 22:00"; 

preg_match_all("/[0-9]+:(?P<minutes>[0-9]+)/", $a, $matches); 

$minutes = array_map(
    function($i) { 
     return intval($i); 
    }, 
    $matches["minutes"] 
); 

var_dump($minutes); 

输出:

array(2) { 
    [0]=> 
    int(10) 
    [1]=> 
    int(0) 
} 
1

您可以使用PHP的DateTime类操作的日期和时间,而不是使用字符串操作。

$time = '10:11'; 
$minutes = DateTime::createFromFormat('H:i', $time)->format('i'); 
echo $minutes; // 11 

因此,对于你的例子:

$hours = "10:11 - 13:34"; 

// Extract times from string 
list($time1, $time2) = explode('-', $hours); 

// Remove white-space 
$time1 = trim($time1); 
$time2 = trim($time2); 

// Format as minutes, and add into an array 
$result = [ 
    DateTime::createFromFormat('H:i', $time1)->format('i'), 
    DateTime::createFromFormat('H:i', $time2)->format('i'), 
]; 

print_r($result); 

=

Array 
(
    [0] => 11 
    [1] => 34 
) 
0

制作使用的strtotime的!这真是强大

<?php 

function getMinuteFromTimes($time){ 
    //strip all white not just spaces 
    $tmp = preg_replace('/\s+/', '', $time); 
    //explode the time 
    $tmp = explode ('-',$tmp); 
    //make our return array 
    $return = array(); 
    //loop our temp array 
    foreach($tmp as $t){ 
     //add our minutes to the new array 
     $return[] = date('i',strtotime($t)); 
    } 

    //return the array 
    return $return; 

} 

print_r(getMinuteFromTimes("7:10 - 22:00")); 
echo '</br>'; 
print_r(getMinuteFromTimes("07:55-14:15")); 
echo '</br>'; 
print_r(getMinuteFromTimes("07:55 -14:15")); 
?> 

输出:
Array ([0] => 10 [1] => 00)
Array ([0] => 55 [1] => 15)
Array ([0] => 55 [1] => 15)

此功能也将接受输入等: “12:00-13:13- 15:12” 或单输入。

相关问题