开发者

How to Remove line if word exists? (PHP)

开发者 https://www.devze.com 2023-02-18 13:47 出处:网络
Hey, I want to remove the whole line if a word exists in it?开发者_StackOverflow中文版 through PHP?

Hey, I want to remove the whole line if a word exists in it?开发者_StackOverflow中文版 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.


$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.


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


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.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号