在PHP sprintf函数中使用带%s字符串的美元符号

在PHP sprintf函数中使用带%s字符串的美元符号,php,wordpress,string,printf,money-format,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_总输出是一个没有美元符号的纯整数。使用$%s或

这涉及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_总输出是一个没有美元符号的纯整数。使用$%s或\$%s不起作用。。如何将美元符号附加到第二个%s变量?

我会:

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

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

您实际上可以在
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 );

?>


工作示例:

在像这样的
$order\u id->get\u total
之前尝试将其浓缩:
sprintf(“%s新客户订单%s,用于%s上的%s”,$blogname,$order->id,“$”。$order->get\u total,$order->order\u date)
'%$%s'
应该可以工作,因为
%
也是sprintf中的转义字符(无论如何,我记得是这样)。已经使用下面的代码片段作为解决方案了,但感谢您的上述测试,对于任何其他正在查看的人都有效!使用下面的解决方案,但连接也有效!感谢您提供的替代方案,在当前环境之外,您已经想到了该方案的用途。