0

I'm trying to use preg_match to pick out two dates from a string (I can't guarantee the string will always be the same, but it will always contain two British dates). An example:

$row['status'] = "Client updated: renewal date changed from 31/01/2015 to 21/02/2015";

The regular expression I'm using worked in an online Regex tester, but I keep getting PHP errors when using it with preg_match.

The initial error: Delimiter must not be alphanumeric or backslash

When I try to change it I get errors like: Unknown modifier '\'

I'm not great with regex, so any help will be apperciated.

$matches = array();
$pattern= '\d{2}/\d{2}/\d{4}';
preg_match($pattern, $row['status'], $matches);
James
  • 788
  • 2
  • 10
  • 28
  • 1
    Use a delimiter that doesn't occur inside your regex pattern, for example: `#`, `~`, `%` etc. – Amal Murali May 30 '14 at 09:13
  • 1
    Enclose the pattern with slash (/) /\d{2}/\d{2}/\d{4}/ – noia_0328 May 30 '14 at 09:14
  • @Amal at the moment, there's no delimiter being used at all! – Tom Fenech May 30 '14 at 09:14
  • 1
    @TomFenech: I know. But the OP tried to use `/`, which generated the error "*Unknown modifier '\'*". That is because the pattern itself contains a forward slash. To avoid the error message, you need to use a delimiter that doesn't occur inside the pattern, or escape *all* the occurrences of the delimiter properly. – Amal Murali May 30 '14 at 09:15
  • @noia_0328: If you're going to use a forward slash as the delimiter, you'll have to escape it inside the regex pattern, like so: `'/\d{2}\/\d{2}\/\d{4}/'`. The pattern in your comment would still generate the "*Unknown Modifier*" error message. – Amal Murali May 30 '14 at 09:17
  • Yeah, as what @AmalMurali suggested, you may instead use %,# since you are already using / or escape it on your pattern. – noia_0328 May 30 '14 at 09:17
  • Hey guys, thanks for the advice, adding a delimiter to the beginning and end gets me pass the error, but it's only picking out 1 date, not two? – James May 30 '14 at 09:23
  • Try to use preg_match_all to capture all matches – noia_0328 May 30 '14 at 09:29
  • cheers @noia_0328, that's done it, guess I just assumed it would already do that, given it outputs an array. Thanks everyone – James May 30 '14 at 09:31

0 Answers0