php-printf和sprintf有不同的输出

php-printf和sprintf有不同的输出,php,Php,我编写了以下微型php程序来测试printf和sprintf: <?php $str_1 = printf("%x%x%x", 65, 127, 245); $str_2 = sprintf("%x%x%x", 65, 127, 245); echo $str_1 . "\n"; echo $str_2 . "\n"; 为什么在输出的第一行有6位数字?不返回字符串,它直接输出字符串(只返回其长度)。试试这个 <?php $text = "6

我编写了以下微型
php
程序来测试
printf
sprintf

<?php
    $str_1 = printf("%x%x%x", 65, 127, 245);
    $str_2 = sprintf("%x%x%x", 65, 127, 245);

    echo $str_1 . "\n";
    echo $str_2 . "\n";
为什么在输出的第一行有6位数字?

不返回字符串,它直接输出字符串(只返回其长度)。试试这个

<?php
    $text = "65 127 245";
    printf("%x%x%x", 65, 127, 245);
    $str_2 = sprintf("%x%x%x", 65, 127, 245);
    echo "\n". $str_2 . "\n";
?>

现在您可能会问,为什么(在您的输出中)会增加6个?因为printf返回打印字符串的长度,在您的案例中为6

这就是它的发展过程

417ff56            // that extra 6 comes from your first echo.
417ff5 

printf:-直接打印格式化字符串

sprintf:-转换给定格式并将值存储在变量中,您可以使用echo/print打印变量值

$text = "65 127 245";
printf("%x%x%x", 65, 127, 245);
$str_2 = sprintf("%x%x%x", 65, 127, 245);
echo $str_2;

您的
$stru_1
包含一个
“6”
-长度,该长度由
printf
417ff56            // that extra 6 comes from your first echo.
417ff5 
$text = "65 127 245";
printf("%x%x%x", 65, 127, 245);
$str_2 = sprintf("%x%x%x", 65, 127, 245);
echo $str_2;