代码之家  ›  专栏  ›  技术社区  ›  Ian

从变量中存储的内容的顶部删除前四行

  •  12
  • Ian  · 技术社区  · 17 年前

    我有一个变量需要在显示前去掉前四行:

    Error Report Submission
    From: First Last, email@example.com, 12345
    Date: 2009-04-16 04:33:31 pm Eastern
    
    The content to be output starts here and can go on for any number of lines.
    

    我需要删除此数据中的“header”,然后将其显示为“挂起的错误报告”视图的一部分。

    4 回复  |  直到 12 年前
        1
  •  22
  •   Paolo Bergantino    17 年前

    嗯。我相信有人会想出一些漂亮/短/好的东西,但是如何:

    $str = implode("\n", array_slice(explode("\n", $str), 4));
    

    如果太难看,你可以把它抽象出来:

    function str_chop_lines($str, $lines = 4) {
        return implode("\n", array_slice(explode("\n", $str), $lines));
    }
    
    $str = str_chop_lines($str);
    

    编辑 :再考虑一下,我不建议使用 str_chop_lines 除非您计划在应用程序的许多部分中执行此操作,否则可以使用。我想,最初的一行已经很清楚了,任何人都会绊倒 斜线 如果不转到函数定义,可能无法实现默认值为4。

        2
  •  4
  •   Bill Fraser    17 年前

    $content = preg_replace("/^(.*\n){4}/", "", $content);

        3
  •  2
  •   Anthony    17 年前

    strpos有很多帮助:下面是一个例子:

    // $myString = "blah blah \n \n \n etc \n \n blah blah";
    
    $len = strpos($myString, "\n\n"); 
    $string = substr($myString, $len, strlen($myString) - $len);
    

    $string然后在一行中查找这两个新行后包含该字符串。

        4
  •  1
  •   Deniz Dogan    17 年前

    使用将字符串拆分为数组 split(rex) 在哪里 rex 匹配两个连续的换行符,然后连接整个数组,第一个元素(即头)除外。

    推荐文章