【问题标题】:Use dollar sign in PHP sprintf function with a %s string在带有 %s 字符串的 PHP sprintf 函数中使用美元符号
【发布时间】:2017-07-09 02:17:06
【问题描述】:

这涉及到 Wordpress 语法,但我认为这主要是 PHP 问题。

我正在使用这个功能:

$subject = sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, $order->get_total, $order->order_date );

产生类似的东西: “SiteName 新客户订单 #3715,7 月 5 日,价格 40.00 美元”

问题是 $order_total 输出为没有美元符号的纯整数。使用 $%s 或 \$%s 不起作用.. 如何将美元符号附加到第二个 %s 变量?

【问题讨论】:

  • 尝试在$order_id->get_total 之前像这样连接它:sprintf( '%s New Customer Order %s for %s on %s', $blogname, $order->id, "$" . $order->get_total, $order->order_date );
  • '%$%s' 应该工作,因为 % 也是 sprintf 中的转义字符(无论如何我记得)。
  • 已经使用下面的 sn-p 作为解决方案,但感谢您的上述,经过测试并适用于其他人!

标签: php wordpress string printf money-format


【解决方案1】:

我愿意:

$currency = '$';
$subject = sprintf( '%s New Customer Order %s for %s%01.2f on %s', 
      $blogname, 
      $order->id, 
      $currency,  
      $order->get_total, 
      $order->order_date );

因此能够更改不同的货币,并将金额格式化为美元和美分(或欧元和美分、英镑和便士等)

【讨论】:

    【解决方案2】:

    您实际上可以在get_total 变量之前连接美元符号$。像这样:

    <?php
    
      //Test class
      class Order{
        public $id = "3333";
        public $get_total = "50.00";
        public $order_date = "07-06-2017";
      }
      $order = new Order();
    
      // Concatenate the dollar sign $ before the $order->get_total variable
      echo sprintf( '%s New Customer Order %s for %s on %s', "Test name", $order->id, "$" . $order->get_total, $order->order_date );
    
    ?>
    

    工作示例:http://sandbox.onlinephpfunctions.com/code/648e6873ebfe9ffc68eb54e61cc2e953be612dca

    【讨论】:

    • 使用下面的解决方案,但串联也有效!谢谢你的替代方案,已经想到了在当前情况之外使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    相关资源
    最近更新 更多