CodexBloom - Programming Q&A Platform

Regex Not Capturing Specific Date Formats in PHP - implementing Custom Separators

πŸ‘€ Views: 81 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
regex php dates PHP

I'm testing a new approach and I'm having trouble with a regex pattern in PHP that should match dates in different formats, specifically ones that use custom separators. The requirement is to capture dates like `12-31-2023`, `31/12/2023`, and `2023.12.31`. However, my current regex only captures the first format correctly. Here's what I've tried: ```php $pattern = '/(\d{2})[-/\.]?(\d{2})[-/\.]?(\d{4})/'; $dates = ['12-31-2023', '31/12/2023', '2023.12.31']; foreach ($dates as $date) { if (preg_match($pattern, $date, $matches)) { print_r($matches); } else { echo "No match for: $date\n"; } } ``` This only successfully matches the first input. The outputs for the other formats result in 'No match for: `31/12/2023`' and 'No match for: `2023.12.31`'. I'm aware that the scenario may be due to the fact that I’m trying to match both the day and month in two different orders, plus I want to support multiple separator characters. I also considered modifying the regex to account for varying positions of day and month, but I'm struggling to come up with a clean solution. I've tried using alternation and grouping, but it gets messy quickly. What’s the best way to handle this while keeping performance in mind? I'm running this on PHP 8.0.3. Any insights would be greatly appreciated! For context: I'm using Php on Ubuntu. I recently upgraded to Php latest.