Jump to content


Photo

Padding the length of a string, help! *SOLVED*


  • Please log in to reply
4 replies to this topic

#1 ecos

ecos
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 27 September 2006 - 07:03 PM

Hello,
I need help padding a string to a certain length, based on its existing length.  I need the string to have a length which is a multiple of 128.  If the string is 100 characters long, I need to pad with 28 characters to equal 128.  If the string is 208 characters, I need to pad it with 48 characters to equal 256, and so on for 384, 512, 640, ...

I know a bit about str_pad(), but I am not sure of a good way to know which multiple of 128 to bump the string length up to.

Thanks for any and all help!
Ecos

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 27 September 2006 - 07:07 PM

<?php 
  $L = strlen($str);
  
  $roundedUp = ceil($L/128)* 128;
    
  str_pad($str, $roundedUp, ' ');
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 ecos

ecos
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 27 September 2006 - 07:20 PM

Barand, you are a true Guru!!
The celi() fucntion looks quite handy. 
Thanks for the help!
Ecos

#4 phporcaffeine

phporcaffeine
  • Members
  • PipPipPip
  • Advanced Member
  • 361 posts
  • LocationOhio, USA

Posted 27 September 2006 - 07:28 PM

This is a a bit more clunky but it explains the logic a little better.

<?php

$length = strlen($string);

if  ($length < 128) {

    $i  =  128 - $length;

    $c = 0;

    while ($c < $i) {

            $c++;

            $string  .= "X";     
     
    }

}

echo $string;

?>
Thanks,

Ryan Huff
President & Founder, MyCodeTree
support@mycodetree.com | http://mycodetree.com

#5 ecos

ecos
  • New Members
  • Pip
  • Newbie
  • 6 posts

Posted 27 September 2006 - 07:48 PM

phpORcaffine,
Thanks for the help. 
This is simialr to what I had come up with, but I needed something that could scale with any size string and any multiple of 128.
Initially I had a series of similar statements with each multiple, but that was extra clunky.

Thanks again,
Ecos 




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users