Skip to content
Advertisement

How to use regular expression to find all numbers starting with “$”

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 “$”?

Advertisement

Answer

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>';

?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement