Michiel
Michiel

Reputation: 8083

preg_match string

Can someone explain me the meaning of this pattern.

preg_match(/'^(d{1,2}([a-z]+))(?:s*)S (?=200[0-9])/','21st March 2006','$matches);

So correct me if I'm wrong:

    ^        = beginning of the line   
    d{1,2}   = digit with minimum 1 and maximum 2 digits  
    ([a-z]+) = one or more letters from a-z
    (?:s*)S  = no idea...  
    (?=      = no idea...
    200[0-9] = a number, starting with 200 and ending with a number (0-9)

Can someone complete this list?

Upvotes: 1

Views: 392

Answers (2)

Ilmari Karonen
Ilmari Karonen

Reputation: 50328

Here's a nice diagram courtesy of strfriend:

^(d{1,2}([a-z]+))(?:s*)S (?=200[0-9])

But I think you probably meant ^(\d{1,2}([a-z]+))(?:\s*)\S (?=200[0-9]) with the backslashes, which gives this diagram:

^(\d{1,2}([a-z]+))(?:\s*)\S (?=200[0-9])

That is, this regexp matches the beginning of the string, followed by one or two digits, one or more lowercase letters, zero or more whitespace characters, one non-whitespace character and a space. Also, all this has to be followed by a number between 2000 and 2009, although that number is not actually matched by the regexp — it's only a look-ahead assertion. Also, the leading digits and letters are captures into $matches[1], and just the letters into $matches[2].

For more information on PHP's PCRE regexp syntax, see http://php.net/manual/en/pcre.pattern.php

Upvotes: 2

Chris Wesseling
Chris Wesseling

Reputation: 6368

regular-exressions.info is very helpful resource.

/'^(d{1,2}([a-z]+))(?:s*)S (?=200[0-9])/

(?:regex) are non-capturing parentheses; They aren't very useful in your example, but could be used to expres things like (?:bar)+, to mean 1 or more bars

(?=regex) does a positive lookahead, but matches the position not the contents. So (?=200[0-9]) in your example makes the regex match only dates in the previous decade, without matching the year itself.

Upvotes: 2

Related Questions