PHP中的可变长度sprintf

时间:2012-10-22 00:37:55

标签: php function native

我正在尝试使用sprintf使PHP变长。这是我使用的代码:

<?php
echo sprinf ("%*s | %*s | %*s | %*s\r\n%*s | %*s | %*s | %*s\r\n",
6,"Monkey", 7,"Cats", 7,"Giraffe", 6,"Goat",
6,"Goat", 7,"Giraffe", 7,"Cats", 6,"Monkey")
?>

预期:

Monkey | Cats    | Giraffe | Goat
Goat   | Giraffe | Cats    | Monkey

结果:

s | s | s | s
s | s | s | s

所以,我创造了自己的功能:

<?php
function _sp($p,$str){
    $pAkhir=$p-strlen($str);
    if($pAkhir<0)$pAkhir=0;
    $pStr=null;for($i=0;$i<$pAkhir;$i++)$pStr.=chr(32);
    return $str.$pStr;
}
?>

因此:

<?php
echo sprintf ("%s | %s | %s | %s\r\n%s | %s | %s | %s\r\n",
_sp(6,"Monkey"),_sp(7,"Cats"),_sp(7,"Giraffe"),_sp(6,"Goat"),
_sp(6,"Goat"),_sp("Giraffe"),_sp(7,"Cats"),_sp(6,"Monkey"))
?>

使用本机PHP函数是否有更有效的方法?

1 个答案:

答案 0 :(得分:0)

我认为@zerkms的答案适合表示:str_pad()。这比编写新函数更有效。

相关问题