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

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to