如何将可变数量的参数传递给sprintf()函数?

时间:2012-03-29 11:16:51

标签: php string printf

在我的网页中,如果用户选择表单中的某些选项,请说

1. A -  Chosen
2. B -  Chosen
3. C -  Not Chosen

然后,我的脚本中的sprintf()函数应该接受该数量的参数 -

sprintf("%s %s", valueOf(A), valueOf(B));

如果选择了所有三个,那么

sprintf("%s %s %s", valueOf(A), valueOf(B), valueOf(C));

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:7)

你想要的可能是vsprintf功能。它将数组作为参数集。所以在你的情况下,你会有这样的事情:

$args = <array_of_chosen_options>;
$fmt = trim(str_repeat("%s ", count($args)));
$result = vsprintf($fmt, $args);

答案 1 :(得分:2)

  1. 动态生成%s %s...字符串
  2. 使用vsprintf代替sprintf
  3. # // FOR DEMONSTRATION \\
    $_POST["A"] = "subscribe_to_this";
    $_POST["B"] = "subscribe_to_that";
    # \\ FOR DEMONSTRATION //
    
    $chosen = array();
    if (isset($_POST["A"])) $chosen[] = $_POST["A"];
    if (isset($_POST["B"])) $chosen[] = $_POST["B"];
    if (isset($_POST["C"])) $chosen[] = $_POST["C"];
    
    $format = implode(" ", array_fill(0, count($chosen), "%s"));
    echo vsprintf($format, $chosen);
    

答案 2 :(得分:0)

sprintf()实际上不是这样做的方法。它适用于带有动态占位符的静态字符串,而不是具有未知数量占位符的动态字符串。

您选择的所有选项,无论您如何收集它们,都可能会以阵列结束。所以你可以implode(),就像这样:

$arr = array(
  'Chosen option',
  'Another option'
  // ...
);

$str = implode(' ', $arr);

是的,你可以vsprintf(),但是为什么要担心产生必须解析和插值的格式字符串的额外开销呢?

答案 3 :(得分:0)

sprintf不是理想的方法。假设您的HTML看起来像

<input type="checkbox" name="options[]" value="A" /> A
<input type="checkbox" name="options[]" value="B" /> B
...

你可以做到

$s = implode(" ", $_POST['options']);
相关问题