How to remove stop words from a string in PHP

1 Answer

0 votes
// A stopwords list is a collection of commonly used words in a language
// that are often removed during text processing tasks. 

function remove_stop_words($arr) {
    $stopWords = array(
        "i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", 
        "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", 
        "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", 
        "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", 
        "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", 
        "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", 
        "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", 
        "between", "into", "through", "during", "before", "after", "above", "below", "to", 
        "from", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", 
        "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", 
        "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", 
        "so", "than", "too", "very", "can", "will", "just", "don", "should", "now"
    );
     
    foreach($stopWords as $word) {
        for ($i = 0; $i < count($arr); $i++)
             if ($arr[$i] == $word)
                $arr[$i] = "";    
    }
     
    $s = implode(" ", $arr);
    
    return trim(preg_replace('/\s+/', ' ',$s));
     
}
 
$s = "a php and java to python a we if c# then a and aa";
 
$arr = explode(" ", $s);
 
echo $s . "\n";
 
$s = remove_stop_words($arr);
 
echo $s;

 
 
/*
run:
 
a php and java to python a we if c# then a and aa
php java python c# aa
 
*/

 



answered Oct 13, 2020 by avibootz
edited Jul 17, 2025 by avibootz
...