Classic ASP (basic) implementation of PHP's sprintf() function


/ Published in: ASP
Save to your folder(s)

This is a basic implementation of PHP's handy sprintf() written in Classic ASP/VBScript. It's not as extensive as PHP's version as it doesn't support numbered parameters, and only works with %s placeholders, but it's better than nothing, right?

Makes for nice clean, understandable code as you can avoid concatenated strings containing function calls mid-string.


Copy this code and paste it in your HTML
  1. <%
  2.  
  3. Function SPrintF(sLine, aReplacements)
  4.  
  5. aLines = Split(sLine, "%s")
  6.  
  7. sFormatted = ""
  8.  
  9. For i = 0 To UBound(aLines)
  10. If UBound(aReplacements) >= i Then
  11. sFormatted = sFormatted & aLines(i) & aReplacements(i)
  12. End If
  13. Next
  14.  
  15. sFormatted = sFormatted & aLines(UBound(aLines))
  16.  
  17. SPrintF = sFormatted
  18.  
  19. End Function
  20.  
  21. ' example usage
  22.  
  23. Response.Write SPrintF("There are %s monkeys in the %s, but only %s lions in the %s.", _
  24. Array("five", "tree", "two", "grass"))
  25.  
  26. Response.Write SPrintF("Click here to visit <a href=""%s"">%s</a>!", _
  27. Array("http://www.google.com", Server.HTMLEncode("Google")))
  28.  
  29. Response.Write SPrintF("SELECT id, name FROM users WHERE username = '%s' AND password = MD5('%s');", _
  30. Array(Replace("sammy", "'", "''"), Replace("letmein", "'", "''")))
  31.  
  32. %>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.