【问题标题】:Regex to replace USD prices in string [duplicate]正则表达式替换字符串中的美元价格[重复]
【发布时间】:2022-01-08 10:42:43
【问题描述】:

我有一个这样的字符串

En babyalarm kan koste alt fra $30 til $20.99, afhængigt af de funktioner, du ønsker. De fleste skærme kommer med et grundlæggende sæt funktioner, koster $3,000.

我需要用计算替换价格。

我有这个代码,但它只获取不包括., 的价格。

$pattern = '#\$(\d*)#';
$string_with_price_replaced = preg_replace_callback($pattern, function($match) {
  return (string)(number_format($match[1]*6.5, 0, "", ""));
}, $string);
echo $string_with_price_replaced;

【问题讨论】:

    标签: php regex


    【解决方案1】:

    试试这个正则表达式来包含小数点和逗号:

    \$(\d+(?:,\d+)*(?:\.\d+)?)
    

    Click for Demo


    说明:

    • \$ - 匹配 $
    • (\d+(?:,\d+)*(?:\.\d+)?)
      • \d+ - 匹配 1 次或多次出现的数字
      • (?:,\d+)* - 匹配 0 次或多次出现的以逗号 (,) 后跟 1+ 位数字的子字符串
      • (?:\.\d+)? - 通过在末尾放置 ? 来匹配数字的小数部分和小数部分

    虽然上面的正则表达式会在匹配的数字中包含,,所以当你尝试对这些数字进行计算时,你会得到一个错误。因此,另一种方法是删除数字之间的逗号,然后执行这些计算,如下面的代码所示:

    $pattern = '#\$(\d+(?:\.\d+)?)#';
    $removeComma = '/(?<=\d),(?=\d)/m';
    $string='En babyalarm kan koste alt fra $30 til $20.99, afhængigt af de funktioner, du ønsker. De fleste skærme kommer med et grundlæggende sæt funktioner, koster $3,000';
    $string = preg_replace($removeComma, '', $string);
    
    $string_with_price_replaced = preg_replace_callback($pattern, function($match) {
        return (string)(number_format($match[1]*6.5, 0, "", ""));
    }, $string);
    
    echo $string_with_price_replaced;
    

    Code output

    【讨论】:

      猜你喜欢
      • 2018-01-16
      • 2023-04-09
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多