Swift: how to censor/filter text entered for swear

2020-07-29 17:14发布

I just want to see whether there is an established way to do this, or how one would go about this.

I have a text field that essentially acts as a form in my iOs app where a user can post something. I can't have users posting swear words/inappropriate crap, so I want to filter out and display an error if the string they enter contains one of these words.

How do other apps in Swift do this? Do they just search through the string to see if it contains the word (obviously not within other words, but standing alone) or is there another method?

How can I accurately filter out the swear words from my user post in Swift?

标签: ios swift
5条回答
淡お忘
2楼-- · 2020-07-29 17:52

Construct a list of words you consider to be swear words, and simply check the user entered string whether any of these words are contained within the string.

Swift 3:

import Foundation

func containsSwearWord(text: String, swearWords: [String]) -> Bool {
    return swearWords
        .reduce(false) { $0 || text.contains($1.lowercased()) }
}

// example usage
let listOfSwearWords = ["darn", "crap", "newb"] 
    /* list as lower case */

let userEnteredText1 = "This darn didelo thread is a no no."
let userEnteredText2 = "This fine didelo thread is a go."

print(containsSwearWord(text: userEnteredText1, swearWords: listOfSwearWords)) // true
print(containsSwearWord(text: userEnteredText2, swearWords: listOfSwearWords)) // false

Swift 2.2:

import Foundation

func containsSwearWord(text: String, swearWords: [String]) -> Bool {
    return swearWords
        .reduce(false) { $0 || text.containsString($1.lowercaseString) }
}

// example usage
let listOfSwearWords = ["darn", "crap", "newb"]
/* list as lower case */

let userEnteredText1 = "This darn didelo thread is a no no."
let userEnteredText2 = "This fine didelo thread is a go."

print(containsSwearWord(userEnteredText1, swearWords: listOfSwearWords)) // true
print(containsSwearWord(userEnteredText2, swearWords: listOfSwearWords)) // false
查看更多
成全新的幸福
3楼-- · 2020-07-29 17:53

Extension checking for foul language.

Swift 4.2

Example Usage:

"poop".containsBadWord()

Extension:

extension String {

    func containsBadWord()->Bool {
        //Sorry for bad words
        let badWords = ["insert","bad","words","here","poop"]
        for word in badWords {
            if lowercased().contains(word) {
                return true
            }
        }
        return false
    }

}
查看更多
混吃等死
4楼-- · 2020-07-29 17:56

I would suggest looking into an API to which you can submit a string and get a JSON response containing information such as:

  • Is the string bad?
  • Total # of bad words contained in string
  • An array containing all recognized bad words
  • A censored version of the input string

I found a couple sources via Google. Check these out and do a little more research to find if an API is the best fit for you and which one you should use. I would assume that using an API like the one I have listed below would be the most practical approach, as you would NOT have to compile a list of "bad" words yourself and use resources from the device to sort through the list (which can contain thousands of words).

Rather, you can simply submit a string using the API to get a network response containing the data in JSON format from the API server.

Why not let the API Server do the logic for you and just spit out an answer?


NeutrinoAPI

查看更多
地球回转人心会变
5楼-- · 2020-07-29 18:00

I created a class that enables you to feed a string in and remove profanity. Here's a link to the repo.

Here's the code:

class ProfanityFilter: NSObject {

    static let sharedInstance = ProfanityFilter()
    private override init() {}

    // Customize as needed
    private let dirtyWords = "\\b(ducker|mother ducker|motherducker|shot|bad word|another bad word|)\\b"

    // Courtesy of Martin R
    // https://stackoverflow.com/users/1187415/martin-r
    private func matches(for regex: String, in text: String) -> [String] {

        do {
            let regex = try NSRegularExpression(pattern: regex, options: [.caseInsensitive])
            let nsString = text as NSString
            let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
            return results.map { nsString.substring(with: $0.range)}
        } catch let error {
            print("invalid regex: \(error.localizedDescription)")
            return []
        }
    }

    public func cleanUp(_ string: String) -> String {
        let dirtyWords = matches(for: self.dirtyWords, in: string)

        if dirtyWords.count == 0 {
            return string
        } else {
            var newString = string

            dirtyWords.forEach({ dirtyWord in
                let newWord = String(repeating: "                                                                    
查看更多
我命由我不由天
6楼-- · 2020-07-29 18:03

If this method returns a range,

str.range(of: "darn|crap|newb", options: [.regularExpressionSearch, .caseInsensitiveSearch], range: str.startIndex..<str.endIndex, locale:nil)

an offensive word has been found. While this method can be used to remove the offending strings:

str.replacingOccurrences(of: "darn|crap|newb", with: "", options: [.regularExpressionSearch, .caseInsensitiveSearch])
查看更多
登录 后发表回答