Randomly Replace Words
September 5th, 2006
I wanted to share a script with everyone that I setup to help someone else randomly replace words in a string. This function will take a string (inputString), then replace occurances of oldKeyword with newKeyword, but not every single time, randomly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <cffunction name="randomReplacement" output="true" returntype="string"> <cfargument name="inputString" type="string" required="yes"> <cfargument name="oldKeyword" type="string" required="yes"> <cfargument name="newKeyword" type="string" required="yes"> <cfset placeHolderNew = '**_NEW_**'> <cfset placeHolderOld = '**_OLD_**'> <cfset listDelims = ' ,.!?'> <cfset newString = inputString> <cfset findOldKeyword = 1> <cfloop condition="findOldKeyword gt 0"> <cfset findOldKeyword = ListFindNoCase(newString, oldKeyword, listDelims)> <cfif findOldKeyword gt 0> <cfif RandRange(1,2) is 1> <cfset newString = ListSetAt(newString, findOldKeyword, placeHolderNew, listDelims)> <cfelse> <cfset newString = ListSetAt(newString, findOldKeyword, placeHolderOld, listDelims)> </cfif> </cfif> </cfloop> <cfset newString = ReplaceNoCase(newString, placeHolderNew, newKeyword, 'ALL')> <cfset newString = ReplaceNoCase(newString, placeHolderOld, oldKeyword, 'ALL')> <cfreturn newString> </cffunction> |
You can test it by running this:
1 2 3 4 | <cfloop index="i" from="1" to="30"> <cfinvoke method="randomReplacement" inputString="My dog is brown, is your dog, sir?" oldKeyword="dog" newkeyword="cat" returnvariable="testing"> <cfoutput>#testing#</cfoutput> </cfloop> |
The listDelims variable can be used to include characters that could be at the end of your word. Please comment if this code ever helps you out. Everyone is free to use it!