CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Numeric Values with Commas in Laravel

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

I keep running into This might be a silly question, but I'm working on a Laravel application where I need to extract numeric values from a string that can include commas as thousand separators..... For example, I need to match strings like "1,234", "56,789.10", or even "123456". I've tried using the following regex pattern: ```php $regex = '/\b\d{1,3}(?:,\d{3})*(?:\.\d+)?\b/'; ``` However, it's not capturing values properly, especially when the number is at the beginning of the string or when there are multiple numeric values in one string. For instance, with the input "The total is 1,234 and the discount is 56,789.10", it only captures "1,234" and ignores the second number. I've also attempted to use the `preg_match_all` function in PHP like this: ```php $input = 'The total is 1,234 and the discount is 56,789.10'; preg_match_all($regex, $input, $matches); print_r($matches); ``` This outputs: ``` Array ( [0] => Array ( [0] => 1,234 ) ) ``` I'm not sure why it's not capturing all the numbers. Can someone guide to adjust the regex pattern or suggest a better approach to ensure that I can extract all numeric values from a mixed string? Any insights or alternative methods would be greatly appreciated! I'm working on a application that needs to handle this. What am I doing wrong? I'd really appreciate any guidance on this.