繁体   English   中英

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

[英]Extract dollar amount from string - regex in 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];

可能是最合适的一个

试试这个:

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-9\.]+))/

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

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

尝试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM