CodexBloom - Programming Q&A Platform

Regex scenarios to Match Specific alphanumeric Patterns in PHP - Need guide with Complex Criteria

👀 Views: 144 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex php validation PHP

I've searched everywhere and can't find a clear answer. I'm trying to validate a custom identifier format in PHP that requires the string to start with three uppercase letters, followed by exactly five digits, and it can optionally end with a two-letter country code (e.g., 'US', 'CA'). The pattern I came up with is: `^[A-Z]{3}\d{5}([A-Z]{2})?$`. However, when I run my test cases, I'm working with unexpected behavior. For example, the string 'ABC12345' matches as expected, but 'ABC12345US' also matches, which is correct. However, 'AB1234' and 'ABC1234A' should not match, but they do. Here is my implementation: ```php $pattern = '/^[A-Z]{3}\d{5}([A-Z]{2})?$/'; $tests = ['ABC12345', 'ABC12345US', 'AB1234', 'ABC1234A', 'XYZ98765CA']; foreach ($tests as $test) { if (preg_match($pattern, $test)) { echo "$test matches\n"; } else { echo "$test does not match\n"; } } ``` I'm using PHP version 7.4. When I run this code, I expect only 'ABC12345' and 'XYZ98765CA' to match, but I'm getting some matches that shouldn't be valid. Any ideas on what might be going wrong with my regex? Am I missing something in my pattern? Also, what are the best practices for testing regex patterns in PHP? Any insights would be greatly appreciated! For context: I'm using Php on Windows.