Mimicking PHP's String Formatting Functions

ASP does not come with many string formatting options. We can find the length, make a string upper/lower case, and do some trimming and replacing, but not too much else. Often appearing in forums is the question "What's the ASP equivalent to PHP's [something] function?" This article will highlight a few formatting functions mimicking PHP, and maybe spur your creative mind on to creating more of your own.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 14
June 21, 2004
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Introduction

Anyone who has ever coded in PHP, knows how easy (and almost fun) it can be to work with strings. The creative minds behind the language realized there are some very common things people like to do with strings, so let's incorporate them right into the package. These include functions to strip HTML formatting, count words, perform smart case changes, and more.

But suppose you make a switch, even a temporary one, to ASP. Perhaps just one application or one environment you work with is ASP driven. Well, much to your dismay, you're now on your own if you want any of these advanced string functions! ASP gives you all you need to trim or count the length of a string, but that's about it. This article will help you along with a number of those functions, and no doubt you'll be able to suggest a few of your own in the forum.

For those of you who don't know or simply don't care what PHP has to offer (shame on you), you'll still find this article very handy. The ideas covered are no doubt things you've encountered in the past, and had to handle in a manual way. My objective here, is to provide some package-able, reusable functions that you can call on whenever you need. And no doubt after you've read of what they can do, you will need!

I'll go through five PHP functions, what they do, and how to create an ASP equivalent. They are:

  • str_word_count
  • ucfirst
  • ucwords
  • strip_tags
  • str_pad

They same imitation is the finest form of flattery, so let us proceed with flattering the PHP designers.

str_word_count and ucfirst

Let me explain the str_word_count function: It counts words.

Yes, simple as that, you feed it a string, and it feeds you back the number of separate words within the string. Here's how we could duplicate it in ASP:

'==================================================

Function strWordCount( strToCount )

'==================================================

Dim arWords


strToCount = Trim( strToCount & "" )

arWords = split( strToCount, " " )

strWordCount = uBound( arWords ) + 1


End Function

Yes, it is really very simple. It just breaks the string by its spaces, as spaces logically define the separation of words. These are broken into an array, and the array is counted to see how many words it's holding. Of course we need to add one to the number, as arrays are zero-based, and we're not.

This will even work if you hand it a string with no spaces. It will not break, the array will contain the entire string as the first item of the array, and the word count will be one. Also, the first line of the function prevents any runtime errors due to handing the function a null value, and it does this by turning it into a string.

So that was simple, let's move on to the next two.

Sometimes it is very important to have proper formatting in a string. One example is when a user enters their City into a form, you may want to match it to a city on your database. It is essential to ensure that you establish and enforce proper formatting. In most cases it would be to have the first letter capitalized, and the rest lowercase. Yes, we can prevent problems caused by the angry people who type in all caps, or the lazy ones like myself who never hit the shift key!

PHP has a great little function call uc_first, which returns a string formatted exactly as I described. Here's a simple way to do exactly the same thing with ASP.

'===================================================

Function ucFirst( strWord )

'===================================================

strWord = trim( strWord & "" )

if len( strWord ) > 0 then

ucFirst = uCase( left( strWord, 1 ) ) & _

lcase( right( strWord, len( strWord ) - 1 ) )

end if

End Function

Going a step further, it was realized that you may have a string containing many words, and you want them ALL to be formatted in this fashion. A good example of this is a title. No matter how a title has been entered, you still want it to look like a title, and so we shall:

'===================================================

Function ucWords( strWords )

'===================================================

strWords = trim( strWords & "" )

if len( strWords ) > 0 then

dim arWords, i, strFormatted

arWords = split( strWords, " " )

for i = 0 to uBound( arWords )

strFormatted = strFormatted & " " & ucFirst( arWords( i ) )

next

ucWords = strFormatted

end if

End Function

So if you handed this function a string like this:

response.write( "i dON'T liKe thiS ARTICLE At all" )

It would come back formatted properly, and the output should be:

"I Love This Article"

Hmm, wishful thinking... if only my functions were that smart! Well then, let's move on.

strip_tags

PHP brings a great function to the table called 'strip_tags'. Through it we can pass a string, and out the other side pops out the stripped-down shadow of its former self. This would be extremely useful in a forum or chat area, where people are constantly trying to throw in some HTML formatting.

There are a couple of ways we could approach this. One would be to flow through the entire string, look for any '<' brackets, and methodically pull away the information around the tags into chunks that can be pieced together separately.

Needless to say, this is a very laborious approach to solving the issue. How much nicer would it be to just use Regular Expressions? A lot, so let's do it! If you need to know more about regular expressions, here's a great tutorial: http://www.devarticles.com/c/a/ASP/The-Complete-Regular-Expression-Guide. But for now we'll use a simple one, just looking for the common brackets that enclose a tag. Here's the function:

'===================================================

Function stripTags( strToStrip )

'===================================================

Dim objRegExp

strToStrip = Trim( strToStrip & "" )

If Len( strToStrip ) > 0 Then

Set objRegExp = New RegExp

objRegExp.IgnoreCase = True

objRegExp.Global = True

objRegExp.Pattern= "<[^>]+>"

strToStrip = objRegExp.Replace(strToStrip, "")

Set objRegExp = Nothing

End If

StripHTMLTags = strToStrip

End Function

So as you read through the lines of code, you should be able to figure it out. We build the regular expression to find any tags, and blow through the entire string replacing the tags with “”. How handy! Now let's move on to the last.

str_pad

PHP has any interesting little function called str_pad. You basically hand any string to the function with the desired length, and it appends spaces to the string until reaching that length. You have the options of specifying the characters to append instead of spaces, and also where to pad (left, right, or both). This would be handy for padding numbers with leading zeros, and perhaps you have other uses.

Unfortunately, ASP does not allow for optional parameters. So if you want to use the default padding of a space, and the default location of padding to the right, just throw in empty quotations as parameters.

There are two functions referenced in the code that may be slightly foreign to you, (isTrulyNumeric & errorMessage) but you can find them explained at: http://www.aspfree.com/c/a/ASP/Easy-Error-Management/

'===========================================

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

So you can see that if it's specified to pad on both left and right, the do loop simply alternates between left and right. At the end of it all, if the resulting string is longer than the desired length, it's trimmed in the proper location.

Therefore, typing in:

response.write( strPad( "dog", 10, "CAT", "" ) )

will output:

dogCATCATC

Conclusion

I hope this article has taught you a very important lesson, ALWAYS look both ways before crossing the road! No wait, wrong lesson. I meant to say, ALWAYS look for a creative and reusable solution to your problem, and if you see something prepackaged in another language or environment, why not make your own version of it?

You should be able to find lots of uses for these functions, but I also hope you find success in creating your own custom (and maybe borrowed) functions as well. Like I mentioned before, feel free to share them in the forum!

blog comments powered by Disqus
ASP ARTICLES

- Using MySQL with ASP
- ADO for the Beginner
- ADO.NET 101: Data Rendering with a DataGrid ...
- Introducing SoftArtisans OfficeWriter 3.0 En...
- Getting Remote Files With ASP
- The Real Basics of Functions in ASP
- Enhancing Readability with ASP
- Mimicking PHP's String Formatting Functions
- Windows Server Hacks 12, 77, and 98
- How to Sort a Multi-Dimensional Array
- Developing an Information Management Tool wi...
- What are Active Server Pages?
- Getting Remote Pages with ASP
- FTP’ing Files with ASP
- Apply Single-Sign-On to Your Application

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials