有没有办法可以使用sprintf()来限制行/字段大小?

时间:2014-07-27 22:23:26

标签: php printf

我编写了下面的一些代码,并想知道是否有一种方法可以限制字段的大小,使其不会溢出到行的边界之外并换行到新行。?

echo "Category    Product Selected" . "\n";
echo "-------------------------------------------------------------------------"."\n";
foreach ($category_page as $key => $value) {
    echo sprintf("%8s    %s",$key,$value) . "\n";
}

请记住,这是针对纯文本电子邮件/文件进行格式化的。

2 个答案:

答案 0 :(得分:1)

谢谢Dagon。

echo "Category    Product Selected" . "\n";
echo "--------------------------------------------------------------------------------"."\n";
foreach ($category_list as $key => $value) {
    $wrap_value = wordwrap($value, 60, "\n            ", TRUE);
    echo sprintf("%8s    %s",$key,$wrap_value) . "\n";
}

我不知道如何轻松添加空格,所以我只是将其添加到换行符中。

示例输出:

Category    Product Selected
--------------------------------------------------------------------------------
       1    4386,4387
       4    14,6,23,16,17
       5    309,335,323,331,313
       6    1004,1003,997,996,1002,1004,1003,997,996,1002,1004,1003,997,
            996,1002,1004,1003,997,996,1002,1004,1003,997,996,1002,1004,
            1003,997,996,1002,1004,1003,997,996,1002,1004,1003,997,996,1
            002,1004,1003,997,996,1002,1004,1003,997,996,1002,1004,1003,
            997,996,1002,1004,1003,997,996,1002,
       7    154,52,124,85,88
       8    266,253,224,180,209
       9    278,284,276,291,275
      10    297

答案 1 :(得分:-1)

这样,用20多个字符剪切文本。

printf("%8s    %.20s\n",$key, $value);