Reputation: 172
I've the following string:
$str = "Tuesday, February 21 at 7:30am at Plano B";
The at Plano B
is optional. I would like to convert it to: TUE 21 FEB 07:30
Upvotes: 1
Views: 540
Reputation: 24989
I'd like to propose a slightly different solution based on the not as oftenly used strptime
. It uses a pre-defined format to parse the string.
Example:
<?php
// Specify a default timezone just in case one isn't set in php.ini.
date_default_timezone_set('America/Vancouver');
$str = "Tuesday, February 21 at 7:30am at Plano B";
if ($time = strptime($str, '%A, %B %e at %l:%M%P')) {
// This will default to the current year.
echo strtoupper(date('D d M H:i', mktime($time['tm_hour'], $time['tm_min'], 0, $time['tm_mday'], $time['tm_mon'])));
}
Output:
SUN 01 SEP 07:30
Upvotes: 1
Reputation: 4415
$str = "Tuesday, February 21 at 7:30am at Plano B";
$time = strtotime(trim(substr($str,0,(strrpos("at"))));
echo "Date: " . strtoupper(date('D d M H:i', $time));
What do you mean by "at Plano B is optional". Is it sometimes there, sometimes not?
Otherwise:
$str = "Tuesday, February 21 at 7:30am at Plano B";
preg_match("/[a-z]+, ([a-z]+ [0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2}[am|pm])/i", $str, $match);
$time = strtotime($match[1] + ' ' + $match[2]);
echo "Date: " . strtoupper(date('D d M H:i', $time));
Is it always either "Plano B" or empty? or can it also be "Plano A" or something completely diffrent?
See here: http://regexr.com?2vvuj
But you are missing the year in the initial string, so can't parse as strtotime. Also you want output without am/pm.. Do you want to use 24 hour time?
This is not a pretty way, but without the year, i dont think we have much choice..
preg_match("/([a-z]+), ([a-z]+) ([0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2})([am|pm])/i", $str, $match);
$day = substr($match[1], 0, 3);
$mon = substr($match[2], 0, 3);
echo strtoupper($day . " " . $match[3] . " " . $mon . " " . $match[4]);
Upvotes: 2
Reputation: 30434
// Strip the last at, if its not a time
if(!preg_match("/at [0-9]+:[0-9]+[ap]m$/", $str)) {
$str = preg_replace("/at [^0-9].*/","",$str);
}
// Then convert to time
$time = strtotime($str);
// Then output in specified format
echo strtoupper(date("D d M h:i", $time));
Upvotes: 0