Reputation: 38
I have the strings below in a feed. I need to match the bold portion and store it in a variable:
UPDATE:
I used the solution provided by @cryptic.
Here are the result:
$titles = array(
"*~Svet~* 12:30PM to 1:30PM",
"Basketball (M and W) vs Cleveland State 6:00PM",
"Christmas for the Kids Celebration! 2:00PM to 4:00PM"
);
foreach ($titles as $title) {
//get date
preg_match('/(\d{1,2}:\d{2}[ap]m)( to \d{1,2}:\d{2}[ap]m)?/i', $title, $match);
//get title
$cleanTitle = preg_split('/([0-1][0-9]|[0-9]):?([0-5][0-9])/', $title);
echo "<p>Title: ".$cleanTitle[0]."<br />Time: ".$match[0]."</p>";
}
//Output
Title: ~Svet~
Time: 12:30PM to 1:30PM
Title: Basketball (M and W) vs Cleveland State
Time: 6:00PM
Title: Christmas for the Kids Celebration!
Time: 2:00PM to 4:00PM
Upvotes: 1
Views: 68
Reputation: 26320
You can solve it using the following regex
.
/\d{1,2}:\d{2}(?:a|p)m(?: to \d{1,2}:\d{2}(?:a|p)m)*/i
Upvotes: 0
Reputation: 15045
// String example 1
$string = 'Ramdom Event Name 12:30PM to 1:30PM';
preg_match('/(\d{1,2}:\d{2}[ap]m)( to \d{1,2}:\d{2}[ap]m)?/i', $string, $match);
echo $match[0]; // outputs 12:30PM to 1:30PM
// String example 2
$string = 'Ramdom Event Name again 2:30PM';
preg_match('/(\d{1,2}:\d{2}[ap]m)( to \d{1,2}:\d{2}[ap]m)?/i', $string, $match);
echo $match[0]; // outputs 2:30PM
same regex expression will match both string examples, and will also fetch the 'to' portion as well.
Upvotes: 2