Ravikumar Sharma
Ravikumar Sharma

Reputation: 3740

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.

Upvotes: 4

Views: 2926

Answers (2)

PhiLho
PhiLho

Reputation: 41152

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.

Upvotes: 4

Toto
Toto

Reputation: 91498

How about:

$price=preg_replace('/^\D+/', '', $money);

Upvotes: 4

Related Questions