CodexBloom - Programming Q&A Platform

Regex Not Matching Specific Currency Formats in PHP - Handling Decimal and Thousands Separators

👀 Views: 78 💬 Answers: 1 📅 Created: 2025-06-06
regex php validation PHP

I tried several approaches but none seem to work... I'm converting an old project and Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to validate various currency formats in PHP using regex, specifically for cases where amounts can include both decimal and thousands separators. I want to match formats like `$1,234.56`, `€1.234,56`, and even `£123456`. However, my current regex seems to unexpected result on certain patterns, especially when different locales are involved. Here's the regex I've been using: ```php $pattern = '/^(\$|€|£)?(\d{1,3}(,\d{3})*|\d+)(\.\d{2}|,\d{2})?$/'; ``` While this works for most cases, it does not accept amounts with different decimal separators based on locale, such as periods for thousands in some regions and commas for decimals. I get unexpected matches like `€1,234.56` being rejected, even though it should be valid. I tried modifying the regex but ended up with more cases that failed. For instance, when I changed the decimal part to accept either `.` or `,`, I found that it incorrectly matched strings like `€123,456.78` which I don't want to allow. Here's a sample of the test cases I have: ```php $test_cases = ['€1.234,56', '$1,234.56', '£123456', '€1,234.56', '$1.234,56']; foreach ($test_cases as $case) { if (preg_match($pattern, $case)) { echo "$case is valid\n"; } else { echo "$case is invalid\n"; } } ``` When I run this, I get the following output: ``` €1.234,56 is invalid $1,234.56 is valid £123456 is valid €1,234.56 is invalid $1.234,56 is invalid ``` As you can see, the pattern fails for `€1.234,56` and `€1,234.56`. I need guidance on how to write a regex that encompasses all these variations correctly. I'm using PHP 8.0. Can anyone guide to refine this regex to handle different currency formats accurately? Any help would be greatly appreciated! What's the best practice here? I'm working on a microservice that needs to handle this. Has anyone dealt with something similar? Any ideas how to fix this? I'm working on a application that needs to handle this. Thanks for your help in advance!