如何隔离可能包含空格的空格分隔值?

时间:2017-06-24 00:38:30

标签: php regex validation delimiter

我有一个输入,用户将按以下格式输入课程表

[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)

所以我尝试使用空格爆炸输入,然后获取返回数组的最后两个值并生成为$room$days,然后我减去原始$schedule中的两个值得到剩余的并将其作为$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);
}

使用上面的代码我得到了我想要的结果,但问题是当用户没有放置DAYS或ROOM文本进行调整时,我没有得到正确的值。

例如此输入值

11:30 am-12:30 pm mwf (no room)

我得到了这个结果:(room:mwf) (days:pm) (times:11:30 am-12:30 )

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

此模式将处理完整字符串并吐出多维数组。您想如何处理结果?

测试代码:(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";
    }
}

输出:

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',
)