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

Chi*_*ude 10 php regex

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

以下是$ str的可能值:

有一个新的$ 66价格目标
有一个新的$ 105.20价格目标
有一个新的$ 25.20价格目标

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

Mar*_*in. 13

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

可能是最合适的一个


Fai*_*Dev 9

试试这个:

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

说明:

"
(?<=     # 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
"
Run Code Online (Sandbox Code Playgroud)