Re: [WD]: PHP Question - any help is appreciated

From: Date: Wed, 29 Aug 2007 22:30:39 +0000
Subject: Re: [WD]: PHP Question - any help is appreciated
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-261516@lists.php.net to get a copy of this message
Dylan Barber wrote:
I am needing to provide back a fixed length file out of a shopping cart system - I can create the file but does anybody have a simple function to pad or truncate a string to a certain length?
Use sprintf() to format your string. $len = 20 //the length you want $str = 'abcde'; The following says to pad the string with the character x to a final length of $len characters or to trim the string to $len characters. The % is simply there to show that the argument is a formatting instruction. The "'x" says to use an x as the padding character (default is a space). The s informs that we're performing this on a string, as opposed to a number. echo sprintf("%'x${len}.${len}s", $str); xxxxxxxxxxxxxxxabcde This one will add the padding to the end (note the minus sign): echo sprintf("%-'x${len}.${len}s", $str); abcdexxxxxxxxxxxxxxx If you want the default space, use: echo sprintf("%${len}.${len}s", $str);
               abcde
Truncate: $str = 'abcdefghijklmnopqrstuvwxyz'; echo sprintf("%'x${len}.${len}s", $str); abcdefghijklmnopqrst You probably want to assign this to a variable so, instead of using echo, do: $padded = sprintf("%'x${len}.${len}s", $str); HTH brian

« previous php.general (#261516) next »