I have an input where a user will enter a class schedule in the following format
[time] [days] [room]
e.g:
7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3)
So I tried exploding the input using space then get the last two values of the returned array and make the as $room
and $days
, then I subtracted the two in the original $schedule
to get the remaining and make it my $time
.
$sched = explode(" ", $schedule);
if(count($sched) <= 3){
echo 'please check schedule format!';
}else{
$room = array_values(array_slice($sched, -1))[0];
$days = array_values(array_slice($sched, -2))[0];
$times = str_replace($days." ".$room, "" ,$schedule);
}
using the code above I'm getting the result I want, but the problem is when the user does not put DAYS or ROOM the text adjusts so I'm not getting the right value.
For example this input value
11:30 am-12:30 pm mwf (no room)
I'm getting this result: (room:mwf) (days:pm) (times:11:30 am-12:30 )
Is there better way to this?
This pattern will process the full string and spit out a multi-dimensional array. How do you want to handle the results?
Test Code: (Demo)
//$sched='7-8 am MWF ROOM1 | 7:30-9:30 am TTH Room2 | 11:30 am-12:30 pm MWF Room3';
$sched='MWF ROOM1 | 7:30-9:30 am Room2 | 11:30 am-12:30 pm MWF';
//$sched='ROOM1 | 7:30-9:30 am | MWF | MTWTHFS';
if(preg_match_all('/(?:^|\| )([^|]*?m)? ?([MTWHFS]*) ?([Rr][Oo]{2}[Mm]\d+)?(?: |$)/',$sched,$out,PREG_SET_ORDER)){
foreach($out as $a){
if(empty($a[1])){
echo "Missing/Invalid Time\n";
}
if(empty($a[2])){
echo "Missing/Invalid Days\n";
}
if(empty($a[3])){
echo "Missing/Invalid Room\n";
}
var_export(array_slice($a,1));
echo"\n\n";
}
}
Output:
Missing/Invalid Time
array (
0 => '',
1 => 'MWF',
2 => 'ROOM1',
)
Missing/Invalid Days
array (
0 => '7:30-9:30 am',
1 => '',
2 => 'Room2',
)
Missing/Invalid Room
array (
0 => '11:30 am-12:30 pm',
1 => 'MWF',
)