0

I am trying to remove string from a .txt file in PHP, and when I do that it leaves blank space. What I tried:

$content = file_get_contents('../admin/accounts.txt');
$content = str_replace('line3', '', $content);
file_put_contents('../admin/accounts.txt', $content);

File before edit:

line1
line2
line3
line4
line5

File after edit:

line1
line2

line4
line5

I want to remove that exact whitespace and file to look like:

line1
line2
line4
line5
Viljamas
  • 5
  • 2

2 Answers2

0

Remove the line including the newline character. Try first with "\n":

$content = str_replace("line3\n", '', $content);   // note the double quotes around _line3\n_

Note that this will not work if there is whitespace between line3 and \n.

Also note that this will not work when removing the last line and there is not "\n" following.

Regex would also work (including the elimination of 'line5'):

$content = "
line1
line2
line3
line4
line5
";

$search = 'line3';

$result = preg_replace("/($search)([ \t]*)(\R?)/i", '', $content);

print_r($result);

// (line3)  -> matches the 'line3' (case-insensitive, see the /i at the end)
// ([ \t]*) -> matches spaces and/or tabs, zweo to unlimited times
// (\R?)    -> matches any newline character or sequence zero or one times
lukas.j
  • 6,453
  • 2
  • 5
  • 24
  • Why are there capture groups if you aren't using them in the replacement? – mickmackusa Jan 29 '22 at 13:21
  • Readability. The alternatives are: _"/($search)(?:[ \t]*)(?:\R?)/i"_ and _"/($search)[ \t]*\R?/i"_, which I both find less readable. – lukas.j Jan 29 '22 at 13:34
  • And [`/$search\h*\R?/i`](https://3v4l.org/X6iSi) ...which is dead simple to read because there is no unnecessary syntax bloating the pattern. – mickmackusa Jan 29 '22 at 13:59
0

What actually is going on is that when you are seeing a file shaped as following:

line1
line2
line3
line4
line5

it actually is something like the following:

line1\n
line2\n
line3\n
line4\n
line5

Personally speaking, I highly prefer using regex and therefore, preg_replace instead of str_replace to overcome this problem. The code I came up with is:

$content = file_get_contents('../admin/accounts.txt');
$replaceString = preg_replace("/line3([\s\r\n]+)?/m", "", $content);
echo $replaceString;

So even if the accounts.txt has the following content this code would work fine!

Input(accounts.txt)

line1
line2
line3
line4
line5
line3 line3
line3
line12

Output by the code

line1
line2
line4
line5
line12
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29