How to remove stop words from array in PHP

1 Answer

0 votes
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', 'up', 'down', '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', 's', 't', 'can',
		'will', 'just', 'don', 'should', 'now'
    );
    
    foreach($stopWords as $word) {
        for ($i = 0; $i < count($arr); $i++)
             if ($arr[$i] == $word)
                $arr[$i] = "";    
    }
    
    return $arr;
}

$s = "a php and java to python a we c# a aa";

$arr = explode(" ", $s);

print_r($arr);

$arr = remove_stop_words($arr);

print_r($arr);





/*
run:

Array
(
    [0] => a
    [1] => php
    [2] => and
    [3] => java
    [4] => to
    [5] => python
    [6] => a
    [7] => we
    [8] => c#
    [9] => a
    [10] => aa
)
Array
(
    [0] => 
    [1] => php
    [2] => 
    [3] => java
    [4] => 
    [5] => python
    [6] => 
    [7] => 
    [8] => c#
    [9] => 
    [10] => aa
)

*/

 



answered Oct 13, 2020 by avibootz

Related questions

1 answer 265 views
1 answer 107 views
1 answer 100 views
1 answer 97 views
1 answer 98 views
2 answers 111 views
...