Jump to content


This topic is now archived and is closed to further replies.


Need help combing strings into one string always same length

Recommended Posts

Ok, I am combining varables to make a label printing file.  I need the width (or count) of the varables to always =40.  For some reason I cant seem to get it to work.  I need to add spaces between varables when total count is < 40 and I need to clip one varable when the total cound is over 40.

Here is what I have..

$n = 40;
$n -= $a;
$n -= 5;  //max length value description, minus some pad space between varables

if (strlen($descript) < $n){
$b=$n-$a; //number of chars extra that need to be added
while ($b){
$descript = $descript . " "; //add spaces to end of string to make = n
if (strlen($descript) > $n){
//clip string to lenght n
$a=substr($descript, 0, $n); //Copy out max lenght of description to a
//combine description and jobnumber on one line and add the minimum space between varables
$descript = $descript . '    ' . $jobnum; 

$thedata = $client;    \\ CSV FILE . ',' . $descript . ',' . $county . "\n";

fwrite($fh, $thedata);

Share this post

Link to post
Share on other sites
Here is a short script that does what I think you're trying to do:
$d = array('Short',str_pad('This string is 34 characters long',34,'*'),
                'This is a very long description that just goes on and on and on and should get trumcated');
foreach($d as $descrip) {
  $jobnumber = rand(1,99999);
  $testlen = strlen($descrip . ' ' . $jobnumber);
  switch(true) {
        case ($testlen == 40):
            echo '[' . $descrip . ' ' . $jobnumber . ']';
        case ($testlen < 40):
            $padlen = 40 - $testlen + strlen($jobnumber);
            $newstr = $descrip . ' ' . str_pad($jobnumber,$padlen,' ',STR_PAD_LEFT);
            echo '['. $newstr .']';
            $trunc = strlen($descrip) - ($testlen - 40);
            $descrip = substr($descrip,0,$trunc);
            $newstr = $descrip . ' ' . $jobnumber;
            echo '['.$newstr.']';
  echo "\n";

This script echos the result, so you will have to modify it to make it work with your input & output.


Share this post

Link to post
Share on other sites
kenrbnsn not sure but i think there might be a possabilty that the same number might come up twice from the rand() statement.

so how does one solve that problam ha.

Share this post

Link to post
Share on other sites
I was just using rand() to get a value for the $jobnumber variable, since I didn't know where this variable was being initialized in the OP's script. It was just an example.


Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.