Search code examples
phparraysregexfilteringpreg-grep

Filter the values in a flat array using a regular expression


I have an array of words and an array of stopwords. I want to remove those words from the array of words that are in the stopwords array, but the code returns all words:

function stopwords($x){
      return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
    };

$filteredArray = array_filter($wordArray, "stopwords");

Why?


Solution

  • $wordArray = ["hello","red","world","is"];
    
    function stopwords($x){
          return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
        };
    
    $filteredArray = array_filter($wordArray, "stopwords");
    var_dump($filteredArray);
    
    # results out:
    array(2) {
       [0] =>   string(5) "hello"   
       [2] =>   string(5) "world"
    }
    

    What do you think it was going to return?

    Is your input '$wordArray' a string, or an array?