Skip to content

Instantly share code, notes, and snippets.

@stevereich
Created October 13, 2012 01:39
Show Gist options
  • Save stevereich/3882849 to your computer and use it in GitHub Desktop.
Save stevereich/3882849 to your computer and use it in GitHub Desktop.
Coldfusion function to substitute bad words entered into a form field for either asterisks or a string of of characters.
<cfscript>
component output=false {
public filters function init(dsn)
description="Initialize component as an object and store as an application variable. This will
make the just a single hit to the database and store the word list in memory to be used anytime."{
variables.datasource = arguments.dsn;
var q = new query();
var badWordQuery = 0;
q.setDatasource(variables.datasource);
q.setName(badWordQuery);
var qResult = q.execute(sql="
SELECT
*
FROM
badwords
ORDER BY CHAR_LENGTH(strBadWord) DESC
");
badWordQuery = qResult.getResult();
variables.badWordList = valuelist(badWordQuery.strBadWord);
variables.goodWordList = valuelist(badWordQuery.strReplaceString);
return this;
}
public struct function filterWords(required string wordString,boolean scramble){
var i = 0;
var newString = arguments.wordString;
var wordList = "";
var returnStruct = {};
var badWord = "";
var replaceWord = "";
for(i=1;i LTE ListLen(variables.badWordList);i++){
badWord = trim(listgetat(variables.badWordList,i,","));
if(arguments.scramble EQ 0){
replaceWord = repeatstring("*", Len(trim(listgetat(variables.goodWordList,i,","))));
}
else{
replaceWord = trim(listgetat(variables.goodWordList,i,","));
}
if(findnocase(badWord,newString)){
wordList = listappend(wordList,badWord,",");
}
newString = replacenocase(newString,badWord,replaceWord,"ALL");
}
returnStruct['oldString'] = arguments.wordString;
returnStruct['newString'] = newString;
returnStruct['wordsRemoved'] = ListChangeDelims(wordList, ", ");
return returnStruct;
}
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment