Filter a set of bad words out of a PHP array

前端 未结 5 694
你的背包
你的背包 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:24

    A regular expression is not really necessary here — it'd likely be faster to use a few stripos calls. (Performance matters on this level because the search occurs for each of the 20,000 names.)

    With array_filter, which only keeps elements in the array for which the callback returns true:

    $data1 = array_filter($data1, function($el) {
            return stripos($el, 'job') === FALSE
                && stripos($el, 'freelance') === FALSE
                && stripos($el, 'project') === FALSE;
    });
    

    Here's a more extensible / maintainable version, where the list of bad words can be loaded from an array rather than having to be explicitly denoted in the code:

    $data1 = array_filter($data1, function($el) {
            $bad_words = array('job', 'freelance', 'project');
            $word_okay = true;
    
            foreach ( $bad_words as $bad_word ) {
                if ( stripos($el, $bad_word) !== FALSE ) {
                    $word_okay = false;
                    break;
                }
            }
    
            return $word_okay;
    });
    

提交回复
热议问题