Skip to content
Advertisement

Find known string in file then add string prior to it

I need to find a known string inside a config file and then add some content(another string) prior to this.

What is the most efficient way to do this?

Example:

$findString = "Find Me";
$newString = "String To Add";

filetomodify.config

aaaaaaaaaaaaaaaa
bbbbbbbb
Find Me
cccccccccccccc
ddddddddddd
eeeeeeeeeeeeeeeee

Desired outcome:

aaaaaaaaaaaaaaaa
bbbbbbbb
String To Add
Find Me
cccccccccccccc
ddddddddddd
eeeeeeeeeeeeeeeee

I’ve been using fopen to access the file but this only allows to prepend or append content, by default with fwrite. I can’t currently think of an efficient way to meet my requirement.

Advertisement

Answer

This question essentially needs two answers:

  • One for the case, that the file is guaranteed to be small enough to be read into memory
  • One for the opposite case

The first version is easily achieved by

$s=file_get_contents('/path/to/file');
$s=str_replace("nFind Men", "nString To AddnFind Men", $s);
file_put_contents('/path/to/file', $s);

The second version needs more work, along the lines of

$in=fopen('/path/to/file', 'rb');
$out=fopen('/path/to/file.tmp', 'wb');
while (($s = fgets($in)) !== false) {
  if ($s == "Find Me") $s="String To AddnFind Me";
  fputs($out, $s);
}
fclose($in);
fclose($out);
unlink('/path/to/file');
rename('/path/to/file.tmp', '/path/to/file');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement