使用 split 函数从 php 数据中用不同的符号分离时间和日期

Separate time and day with different symbol from php data using split function

我在 php 中存储了一系列数据 (class_time)。我希望比较日期和时间以防止主管创建 class 时发生时间冲突。所以我使用 list() & split() 函数来分离我的数据。数据格式为

Fri, 11:00-13:00

这是我用来追踪它的代码。

while($row8=mysqli_fetch_assoc($result8){
    $preclasstime=$row8['class_time'];
    list($day, $starthrs,$startmin,$endhrs,$endmin) = split('[,:-:]', $preclasstime);

    if($day==$_POST['csday']){
        $numstarthrs=(int)$starthrs;
        $numstartmin=(int)$startmin;
        $tottimestart=($numstarthrs*100)+($numstartmin);

        $numendhrs=(int)$endhrs;
        $numendmin=(int)$endmin;
        $tottimeend=($numendhrs*100)+($numendmin);

        echo "$numendmin \n";
    }

但是我执行后,它可以成功获取$day$starthrs$startmin,但是当变成$endhrs$endmin ,它无法正常工作。它将跳过 $endhrs 之一并直接到 $endmin.

例如:

$tottimestart=1100 but $tottimeend=0000, it will ignore the 13.
The answer should be 1300.
If another example such as: Fri, 11:00-13:30 , $tottimeend should be equal to 1330.

我不知道是哪个错误导致它跳过了我的一个值。

你可以像这样轻松地做到这一点,如果你指定的格式总是遵循:

<?php 
$data = "Fri, 11:00-13:30";
list($day,$timingData) = explode(',', $data);
list($startTime,$endTime) = explode('-', $timingData);
$startTime = str_replace(':', '', $startTime);
$endTime = str_replace(':', '', $endTime);

echo "Day: $day <br/>";
echo "startTime: $startTime <br/>";
echo "endTime: $endTime";
?>

输出:

Day: Fri 
startTime: 1100 
endTime: 1330

split() 在 PHP 5.3.0 中被弃用,在 PHP 7.0.0 中被移除。

Alternatives to this function include: preg_split()

这是您问题的解决方案:

$keywords = preg_split('/[\s,\s:\s-\s:\s]+/', "Fri, 11:00-13:30");
$day = $keywords[0];
$tottimestart = $keywords[1]*100 + $keywords[2];
$tottimeend = $keywords[3]*100 + $keywords[4];

echo $day."<br />";
echo $tottimestart."<br />";
echo $tottimeend."<br />";

在转换为整数之前使用连接连接字符串

<?php 
$data = "Fri, 11:00-13:30";
list($day, $starthrs,$startmin,$endhrs,$endmin) = preg_split('[,|:|-]', $data);
echo 'Day: ' . $day;
echo '<br>Start: ' . (int)$tottimestart = $starthrs . $startmin;
echo '<br>End: ' . (int)$tottimesend = $endhrs . $endmin;
?>

将此模式应用于 preg_split():

/[ ,:-]+/

它将使用字符class中的一个或多个字符作为分隔符。这确保了逗号后面的 space 也被删除。

代码:(Demo)

$row8['class_time']='Fri, 11:00-13:00';
var_export(preg_split('/[ ,:-]+/',$row8['class_time']));

输出:

array (
  0 => 'Fri',
  1 => '11',
  2 => '00',
  3 => '13',
  4 => '00',
)

当然,您可以在我有 var_export() 的地方附加您的 list() 电话。