【问题标题】:How to Remove line if word exists? (PHP)如果单词存在,如何删除行? (PHP)
【发布时间】:2011-07-19 15:59:38
【问题描述】:

嘿,如果其中存在单词,我想删除整行?通过 PHP?

例如:hello world, this world rocks。 它应该做的是:如果它找到单词hello,它应该删除整行。 我该怎么做,括号和引号之间也可能有单词。

谢谢。

【问题讨论】:

    标签: php word line exists


    【解决方案1】:

    又好又简单:

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

    【讨论】:

      【解决方案2】:

      如果你有一个这样的行数组

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

      您可以遍历数组并查找单词

      $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

      【讨论】:

      • substr 用于提取字符串的一部分。我想你的意思是strposstrstr
      • 嘘!接下来我会忘记我的内衣。是的,我的意思是stripos,让我的电线交叉
      • 嘿,谢谢约翰的回答。有效。 stripos 函数删除了该行...谢谢
      【解决方案3】:
      $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);
      

      输出

      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.

      你说这个词也可以是括号和逗号之间的词

      如果只想要单词本身,或者在括号和引号之间,您可以用这个替换strstr()...

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

      Ideone.

      我假设括号中的意思是括号,引号是双引号。

      您也可以在多行模式下使用正则表达式,但乍一看这段代码的作用并不明显......

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

      Related Question.

      【讨论】:

      • 嘿亚历克斯...感谢您的回答... preg_replace 函数删除了单词,但未能删除整行?你能告诉我这是在发生吗?我只使用 preg_replace 函数。我没有使用您放置的上述代码。你能告诉我如何将这两者或任何其他方式结合起来,因为我可以删除整行。
      • @Arjun 接受一个答案然后接受另一个答案不是一种好方法(找出最能解决您的问题的答案)。现在不要担心,但下次记住它。
      • 好吧对不起...实际上我对stackoverflow有点陌生...我会记住的...:D谢谢...
      猜你喜欢
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-05
      • 2021-10-03
      • 2017-02-14
      • 2016-02-05
      • 2022-06-21
      相关资源
      最近更新 更多