padding a string with blanks

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    padding a string with blanks

    How do I add blanks to a string?

    I want to evaluate the length of a number (number of digits) and pad the string with blanks depending on the length

    The number can be 1 to 6 digits.

    1) get the length of the number
    2) pad the string with the number of blanks where 6 - string length = number blanks to pad.
    For example
    123 = "123bbb"
    1234 = "1234bb"
    12345 = "12345b"
    123456 = "123456"

    Using the sample code from the online php manual as shown below, I don't get the result they show.

    Code:
    $job = 12345;
    echo 'start-';
    echo printf("[%-10s]\n", $job); // left-justification with spaces
    echo '-end';
    This code gives me:
    start-[12345 ] 13-end

    Not sure why it prints the 13. And I don't see 10 blanks in the result either.
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    #2
    I see I made the mistake of adding echo to the response which gave me the 13.

    But I want to do further massaging of the string, so I just want to capture the string ie: "1234bb" in a variable not actually streaming it out. So I guess I should not be using "sprintf"

    Comment

    • Claus Mygind
      Contributor
      • Mar 2008
      • 571

      #3
      I guess the following code is correct, I hope
      Code:
      <?php
      $job = 12345;
      echo 'start-';
      $padLen = str_pad($job, 6);
      echo $padLen;
      echo '-end';
      echo strlen($padLen)."<br>";
      echo 'start-';
      $padLen = str_pad($job, 10);
      echo $padLen;
      echo '-end';
      echo strlen($padLen)."<br>";

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        you might also find sprintf() feasible (look at example #7).

        But I want to do further massaging of the string, so I just want to capture the string ie: "1234bb" in a variable not actually streaming it out. So I guess I should not be using "sprintf"
        but that’s what sprintf() is doing, it returns a string (into a variable). printf() echoes the string out.
        Last edited by Dormilich; Nov 1 '12, 06:14 AM.

        Comment

        • Claus Mygind
          Contributor
          • Mar 2008
          • 571

          #5
          Yeah! that one is a little harder for me to wrap my brain around. Example 7 was the one I used in my sample code. The str_pad() was just a little easier to understand and to incorporate into my code, where I want to create a string something like this "123bbbsome text".
          (in this example b = space)

          This can easily be coded as
          $myString = str_pad($numVar , 6).$alphaVar;

          Not sure how I would write that with sprintf()?

          Comment

          Working...