我将例程时间存储在数据库表中4-6;6-7
。现在我想解析它并以下列格式显示。我可以使用循环多次爆炸来完成它。但我认为可以用正则表达式完成。我希望输出看起来像这样:
如果数据为4-6;6-7
,则输出应为:
4:00 - 6:00
6:00 - 7:00
如果数据为4:30-6:30;6-7:30
,则输出应为:
4:30 - 6:30
6:00 - 7:30
答案 0 :(得分:1)
不是正则表达式,但结果相同:(爱explode
- 一些屎)
<?php
$str = '4-6;6-7';
$two_t = explode(';',$str);
$first_t = explode('-',$two_t[0]);
$second_t = explode('-',$two_t[1]);
$time = setMinutes($first_t[0]) .'-'.setMinutes($first_t[1]) ."<br/>". setMinutes($second_t[0]) .'-'. setMinutes($second_t[1]);
echo $time;
function setMinutes($time){
$quarter = explode(':',$time);
$hour = $quarter[0];
if(!isset($quarter[1])){
$minutes = '00';
}else{
$minutes = $quarter[1];
}
return "$hour:$minutes";
}
?>
输出:
4:00-6:00
6:00-7:00
<强>已更新强>
根据要求,使用正则表达式:
$str = '4:30-6:30;6-7:30';
echo formatTime($str);
echo "\n\n";
$str = '4-6;6-7';
echo formatTime($str);
function formatTime($str) {
// get all match per group separating each time and minute
preg_match_all('/(\d(:\d\d)?)-(\d(:\d\d)?);(\d(:\d\d)?)-(\d(:\d\d)?)/', $str, $matches);
// remove the whole match
unset($matches[0]);
// loop through the matches and check if minutes(in even keys) exists
foreach ($matches as $key => $value) {
if ($key % 2 == 0) {
$matches[$key - 1][0] = (strlen($value[0]) == 0) ? $matches[$key - 1][0] . ':00' : $matches[$key - 1][0];
}
}
// combine all the time in odd keys
return $matches[1][0] . '-' . $matches[3][0] . "\n" . $matches[5][0] . '-' . $matches[7][0];
}
输出:
4:30-6:30
6:00-7:30
4:00-6:00
6:00-7:00
答案 1 :(得分:1)
您可以使用(?&lt;&#39; NAME&#39;&gt; SUB_PATTERN)访问任何模式组。 结果是一个包含&#39; NAME&#39;的数组。索引。
<?php
$date = "4:30-6:30;6-7:30";
// $date = "4-6;6-7";
$result = '';
$pattern = '/^(?<a>.*)-(?<b>.*);(?<c>.*)-(?<d>.*)$/';
preg_match($pattern , $date , $matches);
$pattern2 = '/^\s*((?<h2>\d+)|(?<h1>\d+:\d+))\s*$/';
preg_match($pattern2 , $matches['a'] , $match);
$result .= ((isset($match['h1'])) ? $match['h1'] : $match['h2'].':00');
$result .= ' - ';
preg_match($pattern2 , $matches['b'] , $match);
$result .= ((isset($match['h1'])) ? $match['h1'] : $match['h2'].':00');
$result .= '<br />';
preg_match($pattern2 , $matches['c'] , $match);
$result .= ((isset($match['h1'])) ? $match['h1'] : $match['h2'].':00');
$result .= ' - ';
preg_match($pattern2 , $matches['d'] , $match);
$result .= ((isset($match['h1'])) ? $match['h1'] : $match['h2'].':00');
echo $result;
答案 2 :(得分:-1)
为什么不使用替换功能? str_replace函数( “ - ”, “:”,$字符串); str_replace(“;”,“ - ”,$ string);