JohnyChew
JohnyChew

Reputation: 147

Error with regex for currency

I have a regex which removes everything and leaves just numbers and a dot. It doesn't work for large numbers.

Eg. It works when the £5.99 is put into it i get 5.99 but for bigger numbers like £48.49 I get .49

I want this to work with numbers as big as £100.99

/[^0-9.]+([0-9]{2}){0,1}/

An input would be something like "this costs £25.95."

The result should be 25.95

Upvotes: 1

Views: 47

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can use

'~(\d+(?:\.\d+))|.~s'

and replace with \1.

See regex demo

This regex replacement will keep only integer and float numbers in the string.

See IDEONE demo:

$re = '~(\d+(?:\.\d+))|.~su'; 
$str = "this costs £25.95."; 
$result = preg_replace($re, '\1', $str);
echo $result;
// => 25.95

Upvotes: 2

Related Questions