Koralek M.
Koralek M.

Reputation: 3341

Remove next empty row from text

From text:

Text...
Target row


Text...

I need remove row with string 'Target row' and the next empty row. So I need to get:

Text...

Text...

Upvotes: 0

Views: 167

Answers (2)

Vyktor
Vyktor

Reputation: 21007

You've got few "big options".

Replace characters within a text:

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

Match results with preg_match_all()

If you need to match more complex patter you could use preg_match_all() with flag PREG_OFFSET_CAPTURE (to get start offset) and than use the same algorithm as previous example (previous should be much more effective).

Use preg_replace

As Tim Pietzcker suggested, but this solution doesn't care about spaces in free row

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

Use explode and next

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

When loading from file with 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
  }
}

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336258

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

if empty lines must really not contain anything, not even spaces/tabs. If spaces/tabs are allowed, use

$result = preg_replace('/^Target row[ \t]*\r?\n[ \t]*\r?\n/m', '', $subject);

Upvotes: 2

Related Questions