Re: : PHP Question - any help is appreciated
- From: ZeldorBlat <zeldorblat@xxxxxxxxx>
- Date: Thu, 30 Aug 2007 02:20:48 -0000
On Aug 29, 6:30 pm, br...@xxxxxxxxxxxxxxxx (brian) wrote:
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
Why not just use the functions that were designed specifically to pad
(str_pad) and truncate (substr) strings?
.
- References:
- Re: [WD]: PHP Question - any help is appreciated
- From: brian
- Re: [WD]: PHP Question - any help is appreciated
- Prev by Date: Re: date formatting
- Next by Date: Re: [PHP] Internet Explorer Caching
- Previous by thread: Re: [WD]: PHP Question - any help is appreciated
- Index(es):
Relevant Pages
|