Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for finding Price from String

I'm trying to extract a Price from a string:

Example:

$money='Rs.109.10';
$price=preg_replace('/[^0-9.]/u', '', $money);
echo $price;

Output of this example

.109.10

I'm expecting following output:

109.10

Help me to find correct regex.

like image 988
Ravikumar Sharma Avatar asked Feb 19 '23 07:02

Ravikumar Sharma


1 Answers

preg_match('/(\d[\d.]*)/', $money, $matches);
$price = $matches[1];

or, better, as @Smamatti's answer suggests:

preg_match('/\d+\.?\d*/', $money, $matches);
$price = $matches[0];

ie. allows only one dot at max in the number. And no need for explicit capture since we want the whole match, here.

like image 188
PhiLho Avatar answered Mar 02 '23 15:03

PhiLho