I have an app that does a fair bit of text-parsing based on free-form user inputs. In this, I run searches on the whole string, and then on the last value of the string separate from the rest of the string. Here is a pair of functions I wrote to getLast
and getSubString
.
<cffunction name="getLast" output="no" returnType="string" access="public" hint="Takes a string and returns the last value by either comma or space, or returns nothing if the string is only one value long">
<cfargument name="str" required="yes" type="string">
<cfset var returnVar = "">
<cfif listLen(arguments.str) GT 1>
<cfoutput>listLen(#arguments.str#)</cfoutput>
<cfset returnVar = trim(listLast(arguments.str))>
<cfelseif listLen(arguments.str, " ") GT 1>
<cfoutput>listLen(#arguments.str#, " ")</cfoutput>
<cfset returnVar = trim(listLast(arguments.str, " "))>
</cfif>
<cfreturn returnVar>
</cffunction>
<cffunction name="getSubString" output="no" returnType="string" access="public" hint="Takes a string and returns the beginning of the string minus the last value">
<cfargument name="str" required="yes" type="string">
<cfset var last = getLast(arguments.str)>
<cfset var lastLen = len(last) + 1>
<cfset var thisLen = len(str) - lastLen>
<cfset var returnVar = str>
<cfif thisLen GTE 1>
<cfset returnVar = trim(mid(str, 1, thisLen))>
</cfif>
<!--- remove trailing commas --->
<cfif right(trim(returnVar), 1) IS ",">
<cfset returnVar = mid(returnVar, 1, len(trim(returnVar)) - 1)>
</cfif>
<cfreturn returnVar>
</cffunction>
And just for fun, some code that was commented out of the second function:
<!---
<cfset var listDelim = ",">
<cfset var i = 0>
<cfset var returnVar = "">
<!--- if the string is longer than one value --->
<cfif len(last)>
<cfif NOT findNoCase(arguments.str, ",")>
<cfset listDelim = " ">
</cfif>
<cfloop from="1" to="#evaluate(listLen(arguments.str, listDelim) - 1)#" index="i">
<cfset returnVar = "#returnVar# #listGetAt(arguments.str, i, listDelim)#">
</cfloop>
<cfset returnVar = trim(returnVar)>
<cfelse>
<cfset returnVar = arguments.str>
</cfif>
--->
Next time I think I'm going to avoid parsing all my own text and just dumping it all into SOLR.