0

Hello is there a way to delete multiple lines from a text file by using php code? for example text.php

<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>
<a>6</a>
<a>7</a>

i would like to delete the first 5 lines without actually using the content to delete.

2
  • 1
    Yes, just get the file and overwrite it with the data, just without the first 5 lines Commented Mar 14, 2016 at 16:47
  • php.net/manual/en/function.fread.php look at the example #2 and #3. Its really easy. Commented Mar 14, 2016 at 16:53

1 Answer 1

1

This should do it:

$file =  "yourfile.txt"
$lines = file( $file );
$less = array_slice($lines, 4);
file_put_contents( $file, $less );

(You can't edit the file particular, you have to overwrite it.)

EDIT: delete 3-5:

$file =  "yourfile.txt"
$lines = file( $file );
$end = array_slice($lines, 4);
array_splice($lines, 2);
$less = array_merge( $lines, $end );
file_put_contents( $file, $less );

See http://php.net/manual/en/function.array-slice.php and http://php.net/manual/en/function.array-splice.php

Sign up to request clarification or add additional context in comments.

1 Comment

i see, what if i were to delete 3-5 not the first 5 lines

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.