2011-09-28 78 views
3

我要像12小時34米45S一個輸出轉向十二時34分45秒PHP正則表達式輸出轉換

此外,如果一個O這些返回空應該是可能是將忽略它。 因此,34m 45s應該是00:34:45並且當然可以使用單個數字,例如1h 4m 1s以及組合單個和兩個數字,例如12h 4m 12s等等。

有人可以幫忙嗎?

這是實際的代碼

$van = $_POST['gespreksduur_van']; $tot = $_POST['gespreksduur_tot']; $regex = '/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/';

 if(preg_match($regex, $van, $match) AND preg_match($regex, $tot, $matches)) 
     { 
      for ($n = 1; $n <= 3; ++$n) { if (!array_key_exists($n, $match)) $match[$n] = 0; } 
      for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; } 

      $van = printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]); 
      $tot = printf("%02d:%02d:%02d", $match[1], $match[2], $match[3]); 

      print($van); 
      print($tot); 

      $data['gespreksduurvan'] = htmlspecialchars($van); 
      $data['gespreksduurtot'] = htmlspecialchars($tot); 

      $smarty->assign('gsv',$data['gespreksduurvan']); 
      $smarty->assign('gst',$data['gespreksduurtot']); 
     } 
+0

除了我的提供的答案,都沒有爲這個字符串'1h 45m'工作。也許有人可以更新他們的正則表達式的答案,以便這個字符串也通過。 – danishgoel

+0

@danishgoel,我更新的答案有效。在我的原創中,我只是在正則表達式中忘記了一個問號,意外地需要秒數。現在它正在工作 –

+0

define * empty *,是'hms'可以接受嗎? – hakre

回答

0

您可以使用正則表達式來提取成分,然後printf()給你怎麼樣的組件格式:

$time = "1h 45m"; 
preg_match("/(\d\d?h ?)?(\d\d?m ?)?(\d\d?s)?/", $time, $matches); 
for ($i = 1; $i <= 3; ++$i) { if (!array_key_exists($i, $matches)) $matches[$i] = 0; } 
printf("%02d:%02d:%02d", $matches[1], $matches[2], $matches[3]); 

正則表達式允許可選組件。 for循環只填充缺省值爲零的任何缺失鍵(以防止未定義的鍵錯誤,當秒或兩分鐘/秒丟失時)。 printf總是打印兩個零的所有組件。

+0

對不起,如果這是一個愚蠢的問題,但你可以打印$出? – user769498

+0

我更新它使用'printf'而不是'sprintf'。它直接輸出。 –

+0

但是作爲參考,你總是可以做'echo $ out;'來顯示一些東西。 –

0

如果你想使用正則表達式,你可以使用preg_replace_callback

<?php 


function callback($matches) 
{ 
    var_dump($matches); 
    if ($matches[2] == "") $matches[2] = "00"; 
    if ($matches[4] == "") $matches[4] = "00"; 
    if ($matches[6] == "") $matches[6] = "00"; 
    return $matches[2] . ":" . $matches[4] . ":" . $matches[6]; 
} 

$str = "12h 34m 45s"; 
$str = preg_replace_callback("`(([0-2]?[0-9])h)?(([0-5]?[0-9])m)?(([0-5]?[0-9])s)?`", "callback", $str, 1); 

echo $str; 
0

這是你如何能做到這一點沒有正則表達式

// function for your purpose 
function to_time($str){ 
    $time_arr = explode(' ', $str); 
    $time_h = '00'; 
    $time_m = '00'; 
    $time_s = '00'; 
    foreach($time_arr as $v){ 
     switch(substr($v, -1)){ 
      case 'h': $time_h = intval($v); break; 
      case 'm': $time_m = intval($v); break; 
      case 's': $time_s = intval($v); break; 
     } 
    } 
    return $time_h . ':' . $time_m . ':' . $time_s; 
} 

//test array 
$time[] = '1h 45s'; 
$time[] = '12h 35m 45s'; 
$time[] = '1m 45s'; 

// output 
foreach($time as $t) 
    var_dump(to_time($t)); 

此輸出

string '1:00:45' (length=7) 
string '12:35:45' (length=8) 
string '00:1:45' (length=7) 
0
$string = "12h 34m 45s"; 
$string = str_replace(array("h","m","s"), array(":",":",""), str_replace(" ", "", $string)); 

echo $string; 

像這樣的東西?

相關問題