在PHP sprintf函数中使用带有%s字符串

时间:2017-07-09 02:17:06

标签: php wordpress string printf money-format

这涉及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变量?

2 个答案:

答案 0 :(得分:0)

我愿意:

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

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

答案 1 :(得分:0)

您实际上可以在$变量之前连接美元符号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