用于从String中查找价格的正则表达式

时间:2021-10-12 21:18:05

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.

帮我找到正确的正则表达式。

2 个解决方案

#1


4  

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

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

或者更好,正如@ Smamatti的回答所示:

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.

即。数字中最多只允许一个点。因为我们想要整个匹配,所以不需要显式捕获。

#2


3  

How about:

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

#1


4  

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

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

或者更好,正如@ Smamatti的回答所示:

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.

即。数字中最多只允许一个点。因为我们想要整个匹配,所以不需要显式捕获。

#2


3  

How about:

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