0

i have a string which is something like

<?php
$string = Monday & SUNDAY 11:30 PM et/pt;
//or
$string = Monday 11:30 PM et/pt;
?>

i want to fetch '11:30 PM' in both the cases for which i guess i cant use explode so what will be the regular expression for this ,,,also please tell me something pretty nice to learn regular expressions. Thanks in advance

Adeel Akram
  • 390
  • 2
  • 4
  • 12
  • 2
    It's simple. Did you try anything yet? (Your title says "customize"). * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Nov 01 '12 at 12:15
  • 1
    try this website : http://regex.inginf.units.it/ – Ionut Flavius Pogacian Nov 01 '12 at 12:58

4 Answers4

1

Credit goes to the commenters below for several fixes to the original approach, but there were still some unresolved issues.

If you want a fixed 2 hour format: (0[0-9]|1[0-2]):[0-5]\d [AP]M

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

to validly match a twelve-our-clock i'd use a regex like below. A twelve-hour-clock goes from 01:00 to 12:59:

$regex = "#\b(?:0[0-9]|1[0-2]):[0-5][0-9] [AP]M\b#i";
Kaii
  • 20,122
  • 3
  • 38
  • 60
  • The second non-capturing subpattern is not useful because you do not have to locate a set of alternatives. You can also add words boundary to improve the performance of the regexp: `#\b(?:0[0-9]|1[0-2]):[0-5][0-9] [AP]M\b#i` – piouPiouM Nov 01 '12 at 13:14
0

Malik, to retrieve time/date you might use premade library regexes, search this query: http://regexlib.com/Search.aspx?k=digit&c=5&m=-1&ps=20

Basically your time fields are similar, (having the same delimiter ':' ), i'd recommend simple regex: \d{1,2}:\d{2} [PA]M to match in the input string. If you want make it case-insensitive use i, pattern modifier. For the basics of regex welcome to read here.

I give you this match function for PHP (i after second slash (/) makes pattern case-insensitive: am, AM, Am, aM will be equal):

  preg_match('/\d{1,2}:\d{2} [PA]M/i', $string, $time);
  print ($time); 

If there might not be a space after digits (ex. 11:30am) or more then one space char., then the regex should look like this: /\d{1,2}:\d{2}\s*[PA]M/i

Igor Savinkin
  • 5,669
  • 8
  • 37
  • 69
-1

this code will give you 11:30 PM

preg_match('$([0-9:]{3,5}) ([AP])M$','Monday & SUNDAY 11:30 PM et/pt',$m);
echo $m['1']." ".$m['2']."M";
MC_delta_T
  • 596
  • 1
  • 9
  • 22