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



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
.



Relevant Pages

  • Re: : PHP Question - any help is appreciated
    ... Use sprintfto format your string. ... 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. ... echo sprintf; ...
    (php.general)
  • Re: Auto truncate a string to be inserted to SQL table
    ... > Actually what I want to do is truncate the string using any method at MSSQL ... The app will insert record to SQL table at the ... If you are calling a SProc from the application, and passing params, ...
    (microsoft.public.sqlserver.programming)
  • Re: set user=%username%
    ... Your most recent feedback confirms that Windows is ... Type this: echo %MyName% ... > usertest=This is a long string. ...
    (microsoft.public.windows.server.general)
  • Re: its not the school home work
    ... I've learned a bit about strong quotes and think I realized when to ... the shell (such as in the $var, but also for the spaces (that ... echo "foo bar" ... you may say that $string does not appear in /list/ context so ...
    (comp.unix.shell)
  • Re: Why is it neccesary to include SqlDbType to the SqlParameter?
    ... The length is used client side to truncate the string. ... >> Try to not specify the size and insert a long string in the DB. ... >>>>> stored procedure into the Sqlparameters? ...
    (microsoft.public.dotnet.general)