简体   繁体   English

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

[英]Extract dollar amount from string - regex in PHP

i am hvaing a challenge trying to do this reliably for all possible strings. 我正在尝试为所有可能的字符串可靠地执行此操作。

Here are the possible values of $str: 以下是$ str的可能值:

There is a new $66 price target 价格目标是新的66美元
There is a new $105.20 price target 价格目标为105.20美元
There is a new $25.20 price target 价格目标是新的25.20美元

I want a new $dollar_amount to extract just the dollar amount from the above sample strings. 我想要一个新的$ dollar_amount来从上面的示例字符串中提取美元金额。 eg $dollar_amount = 66/105.20/25.20 in above cases. 例如,在上述情况下,$ dollar_amount = 66 / 105.20 / 25.20。 How can i reliably do this with a regex statement in PHP? 我如何使用PHP中的正则表达式可靠地执行此操作? Thanks 谢谢

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

will be probably the most suitable one 可能是最合适的一个

Try this: 试试这个:

if (preg_match('/(?<=\$)\d+(\.\d+)?\b/', $subject, $regs)) {
    #$result = $regs[0];
}

Explanation: 说明:

"
(?<=     # 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
"

You need this regular expression: 你需要这个正则表达式:

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

What is the function that meet your needs is up to you. 满足您需求的功能取决于您。

You can find then regex functions for PHP here: http://www.php.net/manual/en/ref.pcre.php 你可以在这里找到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