[英]PHP regex output converting
我想將12h 34m 45s的輸出轉換為12:34:45
它也應該是可能的,如果其中一個返回空,將忽略它。 所以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']);
}
您可以使用正則表達式來提取組件,然后使用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始終使用兩個零打印所有組件。
如果要使用正則表達式,可以使用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;
這就是你如何在沒有正則表達式的情況下做到這一點
// 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)
$string = "12h 34m 45s";
$string = str_replace(array("h","m","s"), array(":",":",""), str_replace(" ", "", $string));
echo $string;
像這樣的東西?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.