从PHP中的字符串 - 正则表达式中提取美元金额

时间:2011-11-23 18:14:43

标签: php regex

我正在尝试为所有可能的字符串可靠地执行此操作。

以下是$ str:

的可能值
  

目标价格为66美元   价格目标为105.20美元   新的25.20美元的目标价格

我想要一个新的$ dollar_amount来从上面的示例字符串中提取美元金额。例如上述案件中$ dollar_amount = 66 / 105.20 / 25.20。我如何使用PHP中的正则表达式可靠地执行此操作?感谢

4 个答案:

答案 0 :(得分:13)

preg_match('/\$([0-9]+[\.,0-9]*)/', $str, $match);
$dollar_amount = $match[1];

可能是最合适的

答案 1 :(得分:9)

试试这个:

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
"

答案 2 :(得分:4)

你需要这个正则表达式:

/(\$([0-9\.]+))/

满足您需求的功能取决于您。

您可以在此处找到PHP的正则表达式函数:http://www.php.net/manual/en/ref.pcre.php

答案 3 :(得分:0)

尝试

#.+\$(.+)\s.+#