2010-03-25 83 views
1

一個特定的單詞,我需要一些代碼,可刪除不包含特定單詞刪除不包含在PHP

,或者我們可以說,只有包含特定單詞保持和/濾波器陣列的所有行刪除所有其他的

哪一個使用較少的資源?

更新:正確的答案,我的問題是

<?php 

$nomatch = preg_grep("/{$keyword}/i",$array,PREG_GREP_INVERT); 

?> 

通知的PREG_GREP_INVERT。

這將導致包含$ array的所有條目的數組($ nomatch),其中找不到$ keyword。

所以你必須刪除反轉並使用它:) $ nomatch = preg_grep(「/ {$ keyword}/i」,$ array);

現在就只能得到具有線條特定詞

+0

相關:http://stackoverflow.com/questions/2267762/delete-the-line-contains-specific-words-phrases-with-php – trante 2013-03-07 17:15:59

回答

1

您可以使用preg_grep

$nomatch = preg_grep("/$WORD/i",$array,PREG_GREP_INVERT); 

更普遍的解決方案是使用array_filter與自定義過濾器

function inverseWordFilter($string) 
{ 
    return !preg_match("/$WORD/i" , $string); 
} 


$newArray = array_filter ( $inputArray, "inverseWordFilter") 

的/ I在該圖案的端部裝置的情況下insenstive,取出它,使其區分大小寫

+0

$ nomatch = preg_grep(「/ $ WORD/i」,$ array,PREG_GREP_INVERT); 不知道如何這一個刪除行包含特定的單詞,我需要它來保存該行並刪除所有其他 – justit 2010-03-25 01:02:09

+0

哈哈我需要刪除該反轉功能 – justit 2010-03-25 01:05:11

+0

preg_grep的作品。謝謝 – trante 2013-03-07 17:30:49

0

由於這是一個簡單的問題,我給你僞代碼,而不是實際的代碼 - 確保你仍然有一些樂趣與它:

Create a new string where you'll keep the result 
Split the original text into an array of lines using explode() 
Iterate over the lines: 
- Check whether the current line contains your specific word (use substr_count()) 
-- If it does, skip over that line 
-- If it does not, append the line to the result 
0
$alines[0] = 'Line one'; 
$alines[1] = 'line with the word magic'; 
$alines[2] = 'last line'; 
$word = 'Magic'; 

for ($i=0;$i<count($alines);++$i) 
{ 
    if (stripos($alines[$i],$word)!==false) 
    { 
     array_splice($alines,$i,1); 
     $i--; 
    } 
} 

var_dump($alines);