删除php中不包含特定单词的所有行

时间:2010-03-25 00:43:38

标签: php

我需要一些可以删除/过滤不包含特定单词

的数组的代码

或者我们可以说只保留包含特定单词并删除所有其他单词

哪一个使用较少的资源????

更新:我的问题的正确答案是

<?php

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

?>

注意PREG_GREP_INVERT。

这将导致一个数组($ nomatch)包含$ array的所有条目,其中找不到$ keyword。

所以你必须删除那个反转并使用它:) $ nomatch = preg_grep(“/ {$ keyword} / i”,$ array);

现在它只会获得具有该特定单词的行

4 个答案:

答案 0 :(得分:1)

您可以将preg_grep与PREG_GREP_INVERT选项

一起使用

答案 1 :(得分: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表示不区分大小写,将其删除以使其区分大小写

答案 2 :(得分: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

答案 3 :(得分: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);
相关问题