2010-03-25 82 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);