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



I had a series of data (class_time) store in php. And I wish to compare the day and time to prevent time collison when supervisor create the class. So I use the list() & split() functions to separate my data. The format of data is

Fri, 11:00-13:00

And this is the code that I use to trace it.

    list($day, $starthrs,$startmin,$endhrs,$endmin) = split('[,:-:]', $preclasstime);



        echo "$numendmin \n";

However, after I execute it, it can obtain the $day, $starthrs, $startmin successfully, but when turn into $endhrs, $endmin, it cannot function well. It will skip one of the $endhrs and directly to the $endmin.

For example:

$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.

I don't know where the error which to cause it to skip one of my value.

4 Answers: 

split() was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

Alternatives to this function include: preg_split()

Here is the solution to your problem:

$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 />";

Use concatenator to join the strings before converting to interger

$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;

You can do it easily like this ,if the format you have specified would follow always:

$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

Apply this pattern to preg_split():

/[ ,:-]+/

It will use one or more of the characters in the character class as the delimiter. This ensures that the space that trails the comma is removed as well.

Code: (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',

Of course, you can attach your list() call where I have var_export().