BlogCFC - Counting Words in an entry
Thursday August 9, 2007 2:26 PM
Word Count:
242
I thought I would add a quick feature to my blog today. I wanted to be able to display the number of words per post. This was way easier than I thought it would be and it was mainly because of the power behind Regular Expressions. I am still new to regex so this may not be completely right but it works so I am going with it. To add this feature to your blog you have to add 1 line in your index on the same line where it displays the date and tags, here is the code.
<cfoutput>| Word Count: #application.blog.getWordCount(body)#</cfoutput>
Then you need to add the following function to the main BlogCFC Component. All we are doing here is reading the entry text, stripping the html tags and counting the words using Java's String method split. The split method actually returns an array of words so a quick arrayLen() will give us the count we are looking for.
<cffunction name="getWordCount" access="public" output="true" returntype="numeric">
<cfargument name="str" type="string" required="true">
<cfset var stripped = REReplace(arguments.str, "<.*?>", "", "all")>
<cfset var words = stripped.split('\W')>
<cfreturn arrayLen(words)>
</cffunction>
<cfargument name="str" type="string" required="true">
<cfset var stripped = REReplace(arguments.str, "<.*?>", "", "all")>
<cfset var words = stripped.split('\W')>
<cfreturn arrayLen(words)>
</cffunction>
Finally just clear the cache by appending ?reinit=1 to the url.
