dounao2829
2015-05-21 17:20
浏览 58
已采纳

将参数插入到字符串中

In PHP, inserting variables into a string can be done by using sprintf. If I have two string variables $a and $b, they can be inserted into another string like this:

$string = sprintf("String containing %s two other strings %s", $a, $b);

Is there a function such that the string can specify the order of the variables inserted? Instead of specifying the format of the inserted variable, I would like to specify which variable to insert. For example like this:

$string = sprintn("String containing %2 two other strings %1 in opposite order", $a, $b);

This would be very useful in combination with gettext, since translators would be able to change the order of the variables in the string. It could also allow for inserting the same variable multiple times, which can be useful.

图片转代码服务由CSDN问答提供 功能建议

在PHP中,将变量插入字符串可以使用 sprintf 。 如果我有两个字符串变量 $ a $ b ,它们可以插入到另一个字符串中,如下所示:

   $ string = sprintf(“包含%s的字符串,其他两个字符串%s”,$ a,$ b); 
   
 
 

是否有一个函数使得字符串可以 指定插入的变量的顺序? 我想指定要插入的变量,而不是指定插入变量的格式。 例如:

  $ string = sprintn(“包含%2的字符串,其他两个字符串%1以相反的顺序排列”,$ a,$ b); 
   
 
 

这与 结合使用非常有用 gettext ,因为翻译人员可以更改字符串中变量的顺序。 它也可以允许多次插入相同的变量,这可能很有用。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsjbest2014 2015-05-21 20:51
    已采纳

    I went for the following solution. By using strtr instead of str_replace it has the advantage of not recursively replacing any occurrences of %n that may be present in the arguments.

    function sprintn($format) {
       $args = [];
       for($i = 1; $i < func_num_args(); ++$i)
          $args["%$i"] = func_get_arg($i);
       return strtr($format, $args);
    }
    
    点赞 打赏 评论
  • dongsheng6056 2015-05-21 17:36

    You can write a util to do it:

    function sprintn($format,$args = array()){
     for ($i=1; i<=count($args); i++){
       $format = str_replace("%".$i, $args[i], $format);
     }
     return $format;
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题