ID: 50851 Updated by: ras...@php.net Reported By: mmaning at practiceinsight dot net -Status: Open +Status: Bogus Bug Type: Output Control Operating System: Linux PHP Version: 5.2.12 New Comment:
%22s pads to 22 chars in case the string is shorter than 22 chars. Nowhere does it say that %22 will truncate a string longer than 22 chars to 22 chars, and in fact it doesn't. Not in any language. Try compiling this: #include <stdio.h> void main(void) { char *str20 = "12345678901234567890"; char *str40 = "1234567890123456789012345678901234567890"; printf("%22s\n",str20); printf("%22s\n",str40); } Just type: make main Then: ./main Previous Comments: ------------------------------------------------------------------------ [2010-01-27 00:03:30] mmaning at practiceinsight dot net Description: ------------ The %s function in sprintf works just like all of the other % commands - except when you attempt to restrict how large the string is. See the code below. Also, this happens for printf as well. It also happens under Linux and Windows. Since %22c doesn't work because %c only does a single character (it returns a null string when trying to use %22c), only %22s can be used. As can be seen from the first of the two lines, when the string passed in is less than 22 characters - it is padded to be 22 characters long. Thus negating anyone's wish to say "The %s function isn't supposed to be used like that." If it wasn't, then the first occurrence would have simply generated "(--------------------)" instead of what it did. Reproduce code: --------------- <?php $s = str_repeat( "-", 20 ); echo sprintf( "My String (%22s) is 22 characters long.\n", $s ); $s = str_repeat( "-", 40 ); echo sprintf( "My String (%22s) is 22 characters long.\n", $s ); exit( 0 ); $s = str_repeat( "-", 20 ); printf( "My String (%22s) is 22 characters long.\n", $s ); $s = str_repeat( "-", 40 ); printf( "My String (%22s) is 22 characters long.\n", $s ); exit( 0 ); ?> Expected result: ---------------- My String ( --------------------) is 22 characters long. My String (----------------------) is 22 characters long. My String ( --------------------) is 22 characters long. My String (----------------------) is 22 characters long. Actual result: -------------- My String ( --------------------) is 22 characters long. My String (----------------------------------------) is 22 characters long. My String ( --------------------) is 22 characters long. My String (----------------------------------------) is 22 characters long. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=50851&edit=1