March 16th, 2006

Mimic PHP's str_pad() function with ASP

PHP has a handy function called str_pad(). You send a string to the function with the desired length, and it appends spaces or any specified characters to the string until reaching that length. You have the options of specifying where to pad (left, right, or both). Here is the equivalent in ASP.
There are two functions in the code that may be foreign, (isTrulyNumeric & errorMessage). You can find them explained here.


'====
Function strPad( strToPad, toLength, padWith, padWhere )
'====
    'padWhere: 1=right, 2=left, 3=both
    strToPad = strToPad & ""
    dim padBoth
    padBoth = false

    if not isTrulyNumeric( toLength ) then
        call errorMessage( "Desired length not specified!")
     else
         toLength = cint( toLength )
    end if

    if padWith = "" then padWith = " "

    if not isReallyNumeric( padWhere ) then
        padWhere = 1
     else
         padWhere = cInt( padWhere )
        if padWhere > 3 or padWhere < 1 then padWhere = 1
         if padWhere = 3 then
            padBoth = true
            padWhere = 1
        end if
    end if

    do until len( strtoPad ) >= toLength
        select case padWhere
         case 1
             strtoPad = strtoPad & padWith
         case 2
             strtoPad = padWith & strtoPad
        end select
        if padBoth then
            if padWhere = 1 then
                padWhere = 2
             else
                 padWhere = 1
            end if
        end if
    loop

    if len( strToPad ) > toLength then
        if ( padBoth and padWhere = 1 ) or ( padWhere = 2 and not padBoth ) then '=== no carriage return here
            strToPad = right( strToPad, toLength )
        else
            strToPad = left( strToPad, toLength )
        end if
    end if

    strPad = strToPad

End Function
Share

One Response to ' Mimic PHP's str_pad() function with ASP '

Subscribe to comments with RSS or TrackBack to ' Mimic PHP's str_pad() function with ASP '.

  1. Daniel said,

    on February 3rd, 2009 at 1:46 pm

    Man, that's a great function!
    Thank you

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word