Not yet rated
Tags:

Problem

You have a long article and want to show the first 20 words and the last 20 words of the article to show as a summary.

Solution

By taking advantage of the fact that ColdFusion runs on Java, we can use java.util.Arrays class to get a range of elements from an array of words.

Detailed explanation

<!--- some dummy text to demonstrate with --->
<cfsavecontent variable="article">
<p>I am just writing some random words here so that I can 
demonstrate using the java.util.Arrays class in ColdFusion. 
As you may know ColdFusion runs on top of java which means 
we can use it in our code. </p>
<p>This is the second paragraph which has even more words 
in it and I'm running out of things to say, but I think 
we should have enough.</p>
</cfsavecontent>

<!--- 
set how many words to show from the start and end of the
full article 
--->
<cfset wordsToShow = 10 />

<!--- 
strip HTML tags 
--->
<cfset article = ReReplaceNoCase( article, "<[^>]*>",
"", "all" ) />

<!--- 
create a java.util.Arrays instance 
--->

<cfset JavaArrayObject = CreateObject( "java",
"java.util.Arrays" ) />

<!--- 
split the article in an array of words using a space
--->
<cfset articleArray = article.Split( " " ) />

<!--- 
copy the first n words of the article 
--->
<cfset startWordArray = JavaArrayObject.copyOf( articleArray,
wordsToShow ) />

<!--- 
copy the last n words of the article 
---> 
<cfset endWordArray = JavaArrayObject.copyOfRange( articleArray,
ArrayLen( articleArray ) - wordsToShow, ArrayLen( articleArray ) )
/>

<!--- 
convert back to a string to display 
--->
<cfset snippet = ArrayToList( startWordArray, " " ) &
"&hellip;<br />&hellip;" & ArrayToList(
endWordArray, " " ) />

<!--- display the snippet --->
<cfoutput>
<p>#snippet#</p>
</cfoutput>

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes