我有一个变量需要在显示前去掉前四行:
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.
在将其显示为“未决错误报告”视图的一部分之前,我需要从该数据中删除“标题”。
嗯。我确信有人会想出一些漂亮/更短/更好的东西,但是怎么样:
$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
功能,除非您打算在应用程序的许多部分执行此操作。我认为,最初的单行代码已经足够清楚了,任何偶然str_chop_lines
发现的人可能不会意识到默认值是 4,而无需转到函数定义。
$content = preg_replace("/^(.*\n){4}/", "", $content);
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 然后在连续找到这两个换行符后包含字符串。
使用 将字符串拆分为一个数组split(rex)
,其中rex
匹配两个连续的换行符,然后连接整个数组,但第一个元素(即标题)除外。