从字符串中提取美元金额 - PHP中的正则表达式
问题描述:
我在为所有可能的字符串可靠地执行此操作提出了挑战。从字符串中提取美元金额 - PHP中的正则表达式
这里是$ str中的可能值:
有一个新的$ 66的目标价
有一个新的$ 105.20的价格目标
有一个新的$ 25.20的目标价
我想要一个新的$ dollar_amount从上面的示例字符串中提取美元金额。例如在上述情况下$ dollar_amount = 66/105.20/25.20。我如何可靠地做到这一点与PHP中的正则表达式?由于
答
preg_match('/\$([0-9]+[\.]*[0-9]*)/', $str, $match);
$dollar_amount = $match[1];
很可能是最合适的一个
答
尝试
#.+\$(.+)\s.+#
答
试试这个:
if (preg_match('/(?<=\$)\d+(\.\d+)?\b/', $subject, $regs)) {
#$result = $regs[0];
}
说明:
"
(?<= # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
\$ # Match the character “\$” literally
)
\d # Match a single digit 0..9
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 1
\. # Match the character “.” literally
\d # Match a single digit 0..9
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
\b # Assert position at a word boundary
"
+0
伟大的解释! –
答
你需要这样的正则表达式:
/(\$([0-9\.]+))/
什么是满足您的需求是由你的功能。
你可以找到那么正则表达式函数PHP这里:http://www.php.net/manual/en/ref.pcre.php
你应该接受的答案你以前的问题。人们更可能想要帮助你。 –
可能重复的[RegEx - 如何提取价格?](http://stackoverflow.com/questions/2430696/regex-how-to-extract-price) – kenorb