Re: [WD]: PHP Question - any help is appreciated
- From: brian@xxxxxxxxxxxxxxxx (brian)
- Date: Wed, 29 Aug 2007 18:30:39 -0400
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
.
- Follow-Ups:
- Re: : PHP Question - any help is appreciated
- From: ZeldorBlat
- Re: : PHP Question - any help is appreciated
- Prev by Date: [PHP] Re: About Session And Cookies
- Next by Date: Re: [PHP] Re: About Session And Cookies
- Previous by thread: Re: [PHP] date formatting
- Next by thread: Re: : PHP Question - any help is appreciated
- Index(es):
Relevant Pages
|