Arjun Bajaj
Arjun Bajaj

Reputation: 1972

How to Remove line if word exists? (PHP)

Hey, I want to remove the whole line if a word exists in it? through PHP?

Example: hello world, this world rocks. What it should do is: if it finds the word hello it should remove the whole line. How can i do that and there could be words in between brackets and inverted commas also.

Thanks.

Upvotes: 1

Views: 1929

Answers (3)

alex
alex

Reputation: 490333

$str = 'Example: hello world, this world rocks.
What it should do is: 
if it finds the word hello it should
remove the whole line. How can i do that and there 
could be words in between brackets and inverted commas also.';

$lines = explode("\n", $str);

foreach($lines as $index => $line) {
   if (strstr($line, 'hello')) {
      unset($lines[$index]);
   }
}

$str = implode("\n", $lines);

var_dump($str);

Output

string(137) "What it should do is: 
remove the whole line. How can i do that and there 
could be words in between brackets and inverted commas also."

CodePad.

You said the word could be could be words in between brackets and inverted commas also too.

In the case of wanting the word only on its own, or between bracket and quotes, you could replace the strstr() with this...

preg_match('/\b["(]?hello["(]?\b/', $str);

Ideone.

I assumed by brackets you meant parenthesis and inverted commas you meant double quotes.

You could also use a regex in multiline mode, however it won't be as obvious at first glance what this code does...

$str = trim(preg_replace('/^.*\b["(]?hello["(]?\b.*\n?/m', '', $str));

Related Question.

Upvotes: 4

JohnP
JohnP

Reputation: 50019

If you have an array of lines like so

$lines = array(
  'hello world, this world rocks',
  'or possibly not',
  'depending on your viewpoint'
);

You can loop through the array and look for the word

$keyword = 'hello';
foreach ($lines as &$line) {
  if (stripos($line, $keyword) !== false) {
    //string exists
    $line = '';
  } 
}

int stripos ( string $haystack , string $needle [, int $offset = 0 ] ) : http://www.php.net/manual/en/function.stripos.php

Upvotes: 1

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

Nice and simple:

$string = "hello world, this world rocks"; //our string
if(strpos($string, "hello") !== FALSE) //if the word exists (we check for false in case word is at position 0)
{
  $string = ''; //empty the string.
}

Upvotes: 0

Related Questions