我在爲所有可能的字符串可靠地執行此操作提出了挑戰。從字符串中提取美元金額 - PHP中的正則表達式
這裏是$ str中的可能值:
有一個新的$ 66的目標價
有一個新的$ 105.20的價格目標
有一個新的$ 25.20的目標價
我想要一個新的$ dollar_amount從上面的示例字符串中提取美元金額。例如在上述情況下$ dollar_amount = 66/105.20/25.20。我如何可靠地做到這一點與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-9\.]+))/
什麼是滿足您的需求是由你的功能。
你可以找到那麼正則表達式函數PHP這裏:http://www.php.net/manual/en/ref.pcre.php
你應該接受的答案你以前的問題。人們更可能想要幫助你。 –
可能重複的[RegEx - 如何提取價格?](http://stackoverflow.com/questions/2430696/regex-how-to-extract-price) – kenorb