RE: [PHP] Filters and sanitizing a regexp
| From: | Boyd, Todd M. | Date: | Thu, 25 Sep 2008 19:57:51 +0000 |
| Subject: | RE: [PHP] Filters and sanitizing a regexp | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-280937@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: richard.heyes@gmail.com [mailto:richard.heyes@gmail.com] On
> Behalf Of Richard Heyes
> Sent: Thursday, September 25, 2008 2:28 PM
> To: Boyd, Todd M.
> Cc: Frank Stanovcak; php-general@lists.php.net
> Subject: Re: [PHP] Filters and sanitizing a regexp
>
> > ...
>
> Hi,
>
> Had to have a play with this. Here's my (somewhat stricter) regex:
>
> preg_match('/((?:[0-3]?[0-9])?\d)-([0-1]?\d)-20\d\d/', '31-12-2000',
> $matches);
> if (!empty($matches[1]) AND $matches[1] > 31) $matches = array();
> if (!empty($matches[2]) AND $matches[2] > 12) $matches = array();
>
> You could probably do the checks for the day and month within the
> regex, but it's late :-)
I don't think that one is quite right... Your optionals (?) are
confusing. Why [0-3]?[0-9] AND the \d? Why [0-9] at all (since \d is
essentially [0-9])? Why use the discarded capture group (?:) since the
[0-3] is already optional?
It's on! :D
<?php
$var = "as12/32/2000df";
$matches = array();
preg_match('#(\d?[0-9])\D*([0-3]?\d)\D*(\d{4})#', $var, $matches);
if(count($matches) != 4 || $matches[1] > 12 || $matches[2] > 31)
$matches = NULL;
?>
MMDDYYYY 4 life, yo! Although, I would honestly prefer it if the world
went to YYYYMMDD as a standard. Just seems to sort itself out more
intuitively to the way I perceive time.
(FYI, I'm not sure about the if() statement working out or not... I'm
assuming PHP will drop through to the "then" part if there aren't 4
elements in the array instead of arbitrarily testing the
possibly-missing elements... but I didn't test that part.)
Also, I used \D* to save space (and confusion). You could just as easily
use (?:-|/) for hyphens or slashes.
Todd Boyd
Web Programmer