Jump to content

Need help combing strings into one string always same length


Hardwarez

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..

[code]
$a=strlen($jobnumber);
$n = 40;
$n -= $a;
$n -= 5;  //max length value description, minus some pad space between varables

if (strlen($descript) < $n){
$a=strlen($descript);
$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
--$b;
}
}
if (strlen($descript) > $n){
//clip string to lenght n
$a=substr($descript, 0, $n); //Copy out max lenght of description to a
$descript=$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);
--$i;
}
[/code]
Here is a short script that does what I think you're trying to do:
[code]<?php
$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 . ']';
            break;
        case ($testlen < 40):
            $padlen = 40 - $testlen + strlen($jobnumber);
            $newstr = $descrip . ' ' . str_pad($jobnumber,$padlen,' ',STR_PAD_LEFT);
            echo '['. $newstr .']';
            break;
        default:
            $trunc = strlen($descrip) - ($testlen - 40);
            $descrip = substr($descrip,0,$trunc);
            $newstr = $descrip . ' ' . $jobnumber;
            echo '['.$newstr.']';
  }
  echo "\n";
}
?>[/code]

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

Ken

Archived

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

×
×
  • Create New...

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.