2017-08-08 8 views
1

私は例のために持っている:数時間から数分を取得する最善の方法?

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

どのようにこの文字列と分を取得するための最良の方法ですか?私はできる...

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

など

を:私は最もその後もすることができる。例えば

$results = array(11, 34); 

のために、配列にそれらを持っているしたいと思い

$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の使用を作ろう!この機能はまた、のような入力を受け付けます
Array ([0] => 10 [1] => 00)
Array ([0] => 55 [1] => 15)
Array ([0] => 55 [1] => 15)

: "12:00-13:13〜15:12" または単一の入力は

<?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")); 
?> 

出力は本当に強力です。

関連する問題