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
Const STR_PAD_LEFT = "LEFT"
Const STR_PAD_RIGHT = "RIGHT"
Const STR_PAD_BOTH = "BOTH"
' Pad a string to a certain length with another string.
function str_pad(input, pad_length, pad_string, pad_type)
dim output
dim difference
output = ""
difference = pad_length - len(input)
if difference > 0 then
select case ucase(pad_type)
case "LEFT"
for i = 1 to difference step len(pad_string)
output = output & pad_string
next
output = right(output & input, pad_length)
case "BOTH"
output = input
for i = 1 to difference step len(pad_string) * 2
output = pad_string & output & pad_string
next
' Not sure if it will step far enough when difference is an odd number, so this next block is just in case.
if len(output) < pad_length then
output = output & pad_string
end if
output = left(output, pad_length)
case else
for i = 1 to difference step len(pad_string)
output = output & pad_string
next
output = left(input & output, pad_length)
end select
else
output = input
end if
str_pad = output
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.
No comments:
Post a Comment