Saturday, September 6, 2008

str_pad

PHP has a very useful function called str_pad(). It allows you to ensure that a string will conform to a specific length by adding characters of your choice on the end of your choice. A good practical example is when you want a number with leading zeros. ASP doesn't have an equivalent function out of the box, but we're going to write one today; as usual, we'll follow the same syntax to make it easy for those who are already familiar with PHP.


ASP

  1. Const STR_PAD_LEFT = "LEFT"
  2. Const STR_PAD_RIGHT = "RIGHT"
  3. Const STR_PAD_BOTH = "BOTH"
  4. ' Pad a string to a certain length with another string.
  5. function str_pad(input, pad_length, pad_string, pad_type)
  6.     dim output
  7.     dim difference
  8.     output = ""
  9.     difference = pad_length - len(input)
  10.     if difference > 0 then
  11.         select case ucase(pad_type)
  12.         case "LEFT"
  13.             for i = 1 to difference step len(pad_string)
  14.                 output = output & pad_string
  15.             next
  16.             output = right(output & input, pad_length)
  17.         case "BOTH"
  18.             output = input
  19.             for i = 1 to difference step len(pad_string) * 2
  20.                 output = pad_string & output & pad_string
  21.             next
  22.             ' Not sure if it will step far enough when difference is an odd number, so this next block is just in case.
  23.             if len(output) < pad_length then
  24.                 output = output & pad_string
  25.             end if
  26.             output = left(output, pad_length)
  27.         case else
  28.             for i = 1 to difference step len(pad_string)
  29.                 output = output & pad_string
  30.             next
  31.             output = left(input & output, pad_length)
  32.         end select
  33.     else
  34.         output = input
  35.     end if
  36.     str_pad = output
  37. end function

Thinking back to my days as a web developer, this was probably the most reused function out of all I'd ever written.


View ASP implementation on Snipplr

No comments: