[英]PHP Using the array_filter
我將盡力解釋我的情況,所以請耐心等待。
我有一個包含單個單詞的數組,例如:
This is a test array
現在我創建了另一個看起來相似但有2個單詞的數組,看起來像這樣:
This is is aa test test array
好的,這是我的問題開始的地方。 我有一系列“常用詞”,這些詞應該從數組中排除。 比方說,那些常用詞會is
和a
用於這個例子。 現在我首先在單個單詞數組上搜索常用單詞,這樣我就可以使用if(in_array($word, $common_words)) continue;
如果它在common_words數組中,它會跳過它。
但這會產生這個數組:
This test test array
但這不是我希望它發生的方式。 它應該是這樣的:
test array
因為在我們開始取出'common_words'之前,這是唯一一個在彼此旁邊有這兩個單詞的人。 (你還在嗎?)
這里的問題是, if(in_array)
我有一個包含2個單詞的數組, if(in_array)
不再起作用。 所以我做了一些研究,偶然發現了array_filter
命令。 我認為這是我需要的,但我完全失去了如何使用/應用它到我的代碼。
我希望我能夠很好地解釋你的問題,如果有人可以幫助我,我會很感激。
提前致謝!
你的猜測是正確的,你可以使用:
$array = ['this is', 'array array', 'an array', 'test array'];
$stop = ['is', 'test'];
$array = array_filter($array, function($x) use ($stop)
{
return !preg_match('/('.join(')|(', $stop).')/', $x);
});
-ie使用array_filter()
排除模式中包含特定單詞的所有項目
這將與過濾一起使用,因為它將匹配正則表達式 ,即從$stop
我們將獲得正則表達式(is)|(test)
一個好主意是分別評估正則表達式,所以不要每次在array_filter()
迭代中評估它,如:
$array = ['this is', 'array array', 'an array', 'test array'];
$stop = ['is', 'test'];
$pattern = '/('.join(')|(', $stop).')/';
$array = array_filter($array, function($x) use ($pattern)
{
return !preg_match($pattern, $x);
});
重要提示#1 :如果您的停用詞可能包含一些將以特殊方式處理正則表達式的特殊字符,則需要使用preg_quote()
如:
$pattern = '/'.join('|', array_map(function($x)
{
return '('.preg_quote($x, '/').')';
}, $stop)).'/';
$array = array_filter($array, function($x) use ($pattern)
{
return !preg_match($pattern, $x);
});
重要提示#2 :如果您的停用詞數組太長,這可能會導致正則表達式編譯失敗,因為它的長度(太大)。 有一些技巧可以克服它,但如果是你的情況,你最好使用strpos()
代替:
$array = array_filter($array, function($x) use ($stop)
{
foreach($stop as $word)
{
if(false!==strpos($x, $word))
{
return false;
}
}
return true;
});
我認為,bes方式,兩個運算符:array_diff和array_unique
$a[] = 'This';
$a[] = 'is';
$a[] = 'is';
$a[] = 'a';
$a[] = 'a';
$a[] = 'test';
$a[] = 'test';
$a[] = 'array';
$excluded = array('is', 'a');
$result = array_diff($a, $excluded); // Remove all excluded words
$result = array_unique($result); // unique values
var_dump($result);
結果:
array (size=3)
0 => string 'This' (length=4)
5 => string 'test' (length=4)
7 => string 'array' (length=5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.