We help IT Professionals succeed at work.

PHP regex   m/d/yyyy  parsing

willsherwood
willsherwood asked
on
Medium Priority
285 Views
Last Modified: 2012-08-13
How can i split a string that begins with a date from the remainder of the string.
the month and day can have one or two digits, but the year will always have four, and slash format is always used.
(I'm splitting an RSS feed string)
m/d/yyyy     mm/dd/yyyy   etc.

i could manually use two explodes or strpos and manually/awkardly parse, but i think some version of regex would be better?

thanks!
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
Show us an example of the date in situ - there may be a better idea than trying to debug a REGEX.

Author

Commented:
4/5/2011 – Congratulations...
11/5/2010 Hanover ...
8/18/2010 FREE...


where ...  is typically another 100-200 chars
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008

Commented:
preg_split('#\d?\d/\d?\d/\d{4}#', $str);
Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
excellent,  that's it!  and thanks for the comments - helps demystify it.
this gives the rest of the string.
which function to extract the date part (i need to have the date in one var and the rest in the second, which you provided)

thanks!
Most Valuable Expert 2011
Author of the Year 2014

Commented:
This might be a little more on point.  Outputs:
ANDSTUFF CAME WITH DATE STRING 4/27/2011
/MORE STUFF CAME WITH DATE STRING 04/01/2010

Thanks for the points, ~Ray
<?php // RAY_temp_willsherwood.php
error_reporting(E_ALL);

// SOME TEST DATA
$dates = array
( '4/27/2011ANDSTUFF'
, '04/01/2010/MORE STUFF'
)
;

// A REGEX
$regex
= '#'           // REGEX DELIMITER
. '\d{1,2}'     // ONE OR TWO DIGITS
. '\/'          // ESCAPED SLASH
. '\d{1,2}'     // ONE OR TWO DIGITS
. '\/'          // ESCAPED SLASH
. '\d{4}'       // 4 DIGITS
. '#'           // END REGEX DELIMITER
;

// TEST EACH CASE
foreach ($dates as $thing)
{
    $arr = preg_match($regex, $thing, $data);
    $new = preg_replace($regex, NULL, $thing);
    echo "<br/>$new CAME WITH DATE STRING {$data[0]}";
}

Open in new window

Author

Commented:
yes yes, perfect.  many thanks!   all set.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.