Reputation: 2060
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
Reputation: 3710
There are two approaches:
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