从文本中删除下一个空行


Remove next empty row from text

来自文本:

Text...
Target row

Text...

我需要删除字符串为"目标行"的行和下一个空行

Text...
Text...

$result = preg_replace('/^Target row'r?'n'r?'n/m', '', $subject);

如果空行必须真的不包含任何内容,甚至不包含空格/制表符。如果允许空格/制表符,请使用

$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);

将结果与preg_match_all()匹配

如果你需要匹配更复杂的模式,你可以使用preg_match_all()和标志PREG_OFFSET_CAPTURE(以获得开始偏移),然后使用与前面的例子相同的算法(前面的应该更有效)。

使用preg_replace

正如Tim Pietzcker所建议的,但此解决方案不关心空闲行中的空间

$result = preg_replace('/^Target row'r?'n's*'r?'n/m', '', $subject);

使用explodenext

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

使用fgets从文件加载时

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