Maciek
Maciek

Reputation: 1992

Regex capture price endings .00 and ,00

I would like to php preg_match and remove all price ending but my regex is not working.

For example,

1201203,00
123,123.23 
12.23
10.00
10

Into

1201203
123,123
12
10
10

Here is the regex I have so far:

[,|.]\d{2}$

Upvotes: 0

Views: 39

Answers (1)

Nick
Nick

Reputation: 147206

Your regex is basically correct, although you don't need the | in your character set, it should just be [,.] (or you could use (\.|,)). So you can just use preg_replace:

$value = preg_replace('/[,.]\d{2}$/', '', $value);

For example:

$values = array('1201203,00', '123,123.23', '12.23', '10.00', '10');
foreach ($values as &$value) {
    $value = preg_replace('/[,.]\d{2}$/', '', $value);
}
print_r($values);

Output:

Array (
    [0] => 1201203
    [1] => 123,123
    [2] => 12
    [3] => 10
    [4] => 10
)

Demo on 3v4l.org

Upvotes: 1

Related Questions