Reputation: 413
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
Upvotes: 0
Views: 98
Reputation: 145482
Your error is just in the function usage:
$matches = preg_match($pattern,$subject);
What you are actually getting there is:
$booleanresult = ...
But you need the third param to preg_match
for the actual outcome:
$bool = preg_match($pattern, $subject, $matches);
And voila, your regex does actually work. I'd additionally recommend the /x
flag to make it a bit more readable though.
Upvotes: 5