Find First Paragraph

Today I had the need to create a script that would find the first paragraph in a string and use this as the extract for a news article.

So, I thought I’d share the ColdFusion code with everyone:

<cfsavecontent variable="paragraphs">
<p>This is the first paragraph.</p>
<p>Here's the second paragraph.</p>
<p>And finally, the third paragraph.</p>
</cfsavecontent>
<cfset request.firstParagraph = findNoCase("</p>",trim(paragraphs)) />
<cfif request.firstParagraph gt 0>
    <cfset request.firstParagraph = request.firstParagraph+3 />
    <cfset request.newsExtract = left(trim(paragraphs),request.firstParagraph) />
<cfelse>
    <cfset request.newsExtract = trim(paragraphs) />
</cfif>
<textarea id="newsExtract" name="newsExtract" cols="40" rows="5">
<cfoutput>#request.newsExtract#</cfoutput>
</textarea>

I hope that others find this useful.

Update: 07 December 2006
I have now turned this into a nifty function:

<cfscript>
function firstParagraph(str)
{
    str = trim(str);
    endTag = findNoCase("</p>", str);
    if (endTag gt 0)
    {
        endTag = endTag + 3;
        extract = left(str, endTag);
    }
    else
    {
        extract = str;
    }
    return extract;
}
</cfscript>

This should make using the code even easier.

Update: 08 December 2006
This function is now available on CFLib.org!

No Comments

Sorry comments are closed for this entry.