Filter a set of bad words out of a PHP array

前端 未结 5 692
你的背包
你的背包 2021-01-16 03:42

I have a PHP array of about 20,000 names, I need to filter through it and remove any name that has the word job, freelance, or project

5条回答
  •  迷失自我
    2021-01-16 04:36

    Personally, I would do something like this:

    $badWords = ['job', 'freelance', 'project'];
    $names = ['JoomlaFreelance', 'PhillyWebJobs', 'web2project', 'cleanname'];
    
    // Escape characters with special meaning in regular expressions.
    $quotedBadWords = array_map(function($word) {
        return preg_quote($word, '/');
    }, $badWords);
    
    // Create the regular expression.
    $badWordsRegex = implode('|', $quotedBadWords);
    
    // Filter out any names that match the bad words.
    $cleanNames = array_filter($names, function($name) use ($badWordsRegex) {
        return preg_match('/' . $badWordsRegex . '/i', $name) === FALSE;
    });
    

提交回复
热议问题