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 Justin Cook Rating: / 14 June 21, 2004
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.
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:
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.
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:
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:
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.
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.
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!