Hi,

I tink I can use PHP's preg_match() function to check if a string is in the format nn/nn/nnnn but I don't know what the syntax would be and I can't get it from the official PHP site. Can anyone provide this, and explain how the systax works?

Thanks in advance.

Ed

1 answer

Ransom 35
1
point
This was chosen as the best answer

Short Answer: $matched = preg_match("/\d{2}\/\d{2}\/\d{4}$/", $subject);

Long Answer:

The syntax for preg_match itself is here. The "pattern" that it mentions is a regular expression. The syntax for regular expressions is here.

The pattern for a single (unknown) digit is a "character class", and can be written either as "[0-9]" or as "\d".

To match more one digit in a row, we could repeat the pattern for a single digit, but it's easier to read if we use the syntax for repetition:

\d{2} means two digits (not necessarily the same)
\d{2,4} means two, three, or four digits

So simplest way to match nn/nn/nnnn would probably be:

$matched = preg_match("/\d{2}\/\d{2}\/\d{4}/", $subject);

$matched would be 1 if there was a match and 0 if there was none. Note that you have to escape the special character "/" by putting a "\" in front of it.

However, this will "match" if that pattern appears anywhere in the string. If you're looking to check if the string has ONLY that pattern, you need to "anchor" the pattern to the beginning and end of the string.

$matched = preg_match("/^\d{2}\/\d{2}\/\d{4}$/", $subject);

Some additional "features" you may want to add:

  • Allow for whitespace (spaces, tabs) at the beginning and end of the string. -- You can use the whitespace character class \s, followed by a *, which matches 0 or more occurrences.
  • Allow months and days to be entered as one digit (3 instead of 03). -- You can use the second repetition syntax from above.
  • Allow years to be entered as two digits instead of four (10 instead of 2010). -- You can do this by putting the pattern for two digits as normal, then another two surrounded by ()?, which causes the contents of the parentheses to be optional (matches 0 or 1 times).

Combining all those would give:

    $matched = preg_match("/^\s*\d{1,2}\/\d{1,2}\/\d{2}(\d{2})?\s*$/", $subject);

Alternate answer: If you're working with dates, you may find the strtotime or date_parse functions helpful.

Answered over 8 years ago by Ransom
  • Thanks Ransom - I couldn't have asked for a better answer! I've bookmarked this for future reference. Thanks again! Edward Williams over 8 years ago