justit
justit

Reputation: 13

Delete all lines that doesn't contain a specific word in php

i need some code which can delete/filter arrays which doesn't contain a specific word

or we can say keep only that contain a specific word and drop all other ones

which one use less resource ????

update : the correct answer to my problem is

<?php

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

?>

Notice the PREG_GREP_INVERT.

That will result in an array ($nomatch) that contains all entries of $array where $keyword IS NOT found.

so you have to remove that invert and use it :) $nomatch = preg_grep("/{$keyword}/i",$array);

now it will get only that lines which have that specific word

Upvotes: 1

Views: 1137

Answers (4)

Alex Weinstein
Alex Weinstein

Reputation: 9891

Since this is such a simple problem, I'll give you pseudo-code instead of the actual code - to make sure you still have some fun with it:

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

Upvotes: 0

SteelBytes
SteelBytes

Reputation: 6965

$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);

Upvotes: 0

Charles Ma
Charles Ma

Reputation: 49171

You can use preg_grep with

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

A more general solution is to use array_filter with a custom filter

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


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

The /i at the end of the pattern means case insenstive, remove it to make it case sensitive

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342463

you can use preg_grep with PREG_GREP_INVERT option

Upvotes: 1

Related Questions