I'm having a problem with PHP regular expression matching.
The problem I'm trying to solve is I that I need to get a decimal value from a string. The expression needs to meet all the following (all dollar signs optional):
($)1234.56
($)1,234.56
($)1.00
($)10
($).49
($)1,234,567.32
($)1,234,567
After finding some wonderful examples online, I was able to Frankentstein this expression together:
/(?:^|\s|\$)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[0-9])?|0?\.\d*[0-9]|0)(?:\s|$)/
If you use this preg_match tester on solmetra, using the above pattern and the test string 'per unit price $19198.01 hey!' you will will get the following result:
Array
(
[0] => $19198.01
[1] => 19198.01
)
Which is great - it's exactly what I need!
However, when I run the below code in PHP 5.3.10, I get null as an output for matches using this pattern string:
Code:
$pattern = '/(?:^|\s|\$)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[0-9])?|0?\.\d*[0-9]|0)(?:\s|$)/';
$subject = 'per unit price $19198.01 hey!';
$matches = preg_match($pattern,$subject);
var_dump($matches[0]); //dumps "null"
I'm sure I'm doing something wrong, but I just can't see it.
Any help would be greatly appreciated.
Environment:
PHP 5.3.10
Apache 2.2.21
Windows 2008 Server