Reputation: 121
I'm dealing with strings that contain non-comma-separated dollar values. For example:
"LOT 2 - $650000"
I need to be able to find the "$650000" and replace it with "$650,000".
The problem is, I'm a complete novice when it comes to regular expressions. I found a post that suggested this for finding numbers:
preg_match_all('!\d+!', $string, $matches);
This does successfully find both the "2" and the "650000" in my string. However, I want to make sure I only get numbers that start with "$", so I only want to get the "$650000".
Can anyone help me adapt the regular expression to get only numbers that start with "$"?
Upvotes: 0
Views: 82
Reputation: 1934
Kevin's answer is better. I went the long way around:
<?php
$dollarString = 'I would like $100000000000 more than I would like $10000000 but that is still better than $1000 and $99 problems.';
echo '<p>dollarString: ';
var_dump($dollarString);
echo '</p>';
function addCommas ($matches){
$output = [];
$number = $matches[1];
$j = 1;
for($i=strlen($number)-1; $i>=0; $i--){
array_push($output, $number[$i]);
if($j%3 == 0 && $i != 0 && $i != strlen($number)-1){array_push($output, ',');}
$j++;
}
array_push($output, '$');
$output = array_reverse($output);
return implode($output);
}
$newString = preg_replace_callback('#\$(\d+)#', 'addCommas', $dollarString);
echo '<p>newString: ';
var_dump($newString);
echo '</p>';
?>
Upvotes: 1
Reputation: 1
Try the following:
preg_match_all('!\$\d+!', $string, $matches);
This website really helped me understand how to achieve this
Upvotes: 0
Reputation: 110685
You could replace matches of the following regular expression with a comma to both confirm the presence of the dollar sign and to insert commas in the correct locations.
/(?:\$|\G)\d+?\K(?=(?:\d{3})+$)/
The PCRE engine performs the following operations.
(?: : begin non-capture group
\$ : match '$'
| : or
\G : assert position at the end of the previous match
) : end non-capture group
\d+? : match 1+ digits
\K : reset starting point of match and no longer include
previously-consumed characters in reported match
(?= : begin positive lookahead
(?:\d{3}) : match 3 digits in a non-capture group
+ : execute non-capture group 1+ times
$ : match end of string
) : end positive lookahead
Upvotes: 1
Reputation: 41875
Just add the dollar sign in your pattern and use preg_replace_callback
then combine number_format
. Something like this:
$string = preg_replace_callback('~\$(\d+)~', function($matches) {
return !empty($matches[1]) ? '$' . number_format($matches[1]) : null;
}, $string);
Upvotes: 1