我有例如:
$hours = "10:11 - 13:34";
使用此字符串获取分钟的最佳方法是什么?我最想将它们放在数组中,例如
$results = array(11, 34);
然后也可以是:
$hours = "7:10 - 22:00";
$hours = "07:55-14:15";
$hours = "07:55 -14:15";
等...
我可以:
$expl = explode('-', trim($hours));
然后由":"爆炸,但也许是更好的方式?
答案 0 :(得分: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 :(得分: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
)
答案 2 :(得分: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”或单个输入。