felipe.zkn
felipe.zkn

Reputation: 2060

PHP - Write string in a certain position of a file

I have the following string in a text file:

<!-- 
///////////////////////////////////////////////////////////////////////////////////////
//
// Individuals
//
///////////////////////////////////////////////////////////////////////////////////////
 -->

I need to write text two lines below the above part. There are many other sections like the one above, but each one doesn't repeat, so I know there is only one "Individuals".

I need to overwrite the file, so how can I set the position of my output to there?

Upvotes: 1

Views: 1125

Answers (1)

peter_the_oak
peter_the_oak

Reputation: 3710

There are two approaches:

  1. Read the file line by line. Check each line if it matches to certain conditions. If yes, insert lines.
  2. Read the full file, replace the text wanted and write the full file.

As long as your traffic is not too high, method 2 will be simpler. In order to replace the full block, I suggest this regex:

/(<!--[\s\r\n/]*Individuals[\s/]*)[^\s/]*([\s/]*-->)/

It matches the full block containing "Individuals" followed by some content on the new line. The block before the separate content is being caught by parenthesis, in order to do a replace:

$content = file_get_contents('myfile.txt');
$newContent = preg_replace("@(<!--[\s\r\n/]*Individuals[\s/]*)[^\s/]*([\s/]*-->)@", "$1$myNames$2", $content);    
file_put_contents('myfile.txt', $newContent);

The preg_replace concatenates the first part of the block, some slashes and "Individuals", together with $myNames, and together with the closing part of the block to a new block.

I have not tested this finally in the shell, so I apologize for a possible typo. But I'm sure this will work out.

Upvotes: 2

Related Questions