I am parsing quite a bit of data that has the format Monday-Thursday or Tuesday-Saturday. How can I format that into an array of the included days without a ton of regex's? Maybe similarly for times such as 11am-8pm
CodePudding user response:
You don't need any regex to do that. You need the build-in date and time classes:
$str = 'Monday-Thursday';
list($begin, $end) = explode('-', $str);
$begin = new DateTime($begin);
$end = new DateTime($end);
$end = $end->modify(' 1 day');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$result = [];
foreach($daterange as $date){
$result[] = $date->format('l');
}
print_r($result);
Of course, if you want to give your code a little American look, you can use array_map instead of foreach.
$result = array_map(fn($d) => $d->format('l'), iterator_to_array($daterange));
Same thing for hours:
$str = '11am-8pm';
list($begin, $end) = explode('-', $str);
$begin = new DateTime($begin);
$end = new DateTime($end);
$end = $end->modify(' 1 hour');
$interval = new DateInterval('PT1H');
$daterange = new DatePeriod($begin, $interval, $end);
$result = array_map(fn($d) => $d->format('ga'), iterator_to_array($daterange));
print_r($result);
All you have to know are the different date/time formats that are in the PHP manual.
Note that if you want to go from 11pm to 1am, you need to add a day to the $end object.
CodePudding user response:
What about making two from-to variables by exploding the string by "-", then convert the day to number?
