Php 从文本中删除下一个空行

Php 从文本中删除下一个空行,php,regex,replace,Php,Regex,Replace,原文: Text... Target row Text... 我需要删除带有字符串“目标行”的行和下一个空行。所以我需要得到: Text... Text... 如果空行不能包含任何内容,甚至不能包含空格/制表符。如果允许使用空格/制表符,请使用 $result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject); 你几乎没有什么“大选择” 替换文本中的字符: 将结果与 如果需要匹配更复杂的模式,可以

原文:

Text...
Target row


Text...
我需要删除带有字符串“目标行”行和下一个空行。所以我需要得到:

Text...

Text...
如果空行不能包含任何内容,甚至不能包含空格/制表符。如果允许使用空格/制表符,请使用

$result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject);
你几乎没有什么“大选择”

替换文本中的字符: 将结果与 如果需要匹配更复杂的模式,可以使用带有标志的
preg\u-match\u-all()
(获取开始偏移量),而不是使用与前一个示例相同的算法(前一个应该更有效)

使用 正如Tim Pietzcker所建议的,但是这个解决方案并不关心空闲行中的空间

使用及 使用从文件加载时
你的断线是什么<代码>\n或
\r\n
?您使用的是什么输入格式(文本、行数组?)以及如何检测“目标行”?文本来自textarea。目标行由字符串“Target row”检测。您可以使用
\s*
,不是吗?或者它还会吃新线吗?(
\s*?
than)@Vyktor:是的,他只想删除一行空行。而
\s*?
是无用的,因为它最好匹配空字符串,因此不会删除任何内容。
$result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject);
$req = ''; // Partial string to get matched
$length = 0; // If you had a full string not partial, use strlen here

// Now find beginning, don't forget to check with === false
$pos = strpos( $text, $req);
$end = strpos( $text, "\n", $pos+1);

// If you don't have criteria that match from start
$start = strrpos( $text, "\n", $pos-1);
// And build resulting string (indexes +/-2, do your job):
$result = substr( $text, 0, $start-1) . substr( $text, $end+2);
$result = preg_replace('/^Target row\r?\n\s*\r?\n/m', '', $subject);
$array = explode( "\n", $text);
// I would use this only when loading file with:
$array = file( 'file.txt');

while( $row = next( $array)){
  if( matches( $row)){ // Apply whatever condition you need
    $key1 = key( $array);
    next( $array); // Make sure it's not === false
    $key2 = key( $array);

    unset( $array[$key1]);
    unset( $array[$key2]);
    break;
  }
}
$fp = fopen( 'file.txt', 'r') or die( 'Cannot open');
while( $row = fgets( $fp)){
  if( matched( $row)){
    fgets( $fp);// Just skip line
  } else {
    // Store row
  }
}