Reputation: 29
Could anyone give me some ideas or solution for toggling comments in file? To read value and toggle comment/uncomment in that line where value resides.
For example, I would like to include class Model and initialize it.
In some file there are prepared includes and initializations:
//include('foo/Model.php');
//$model = new Model();
Function is needed, for those who can not understand what the question is.
How to uncomment?
Upvotes: 0
Views: 1358
Reputation: 2007
Thanks for adding more insights to your question! Actually it's a pretty interesting one.
As far as I understand you're looking for a dynamic way to comment/uncomment lines inside a file.
So let's define our parameters first:
function file_toggler(string $file, array $lineNumbers)
With this in mind I we need to read a file and split their lines into line numbers. PHP provides a handy function for this called file()
.
file(): Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached.
With this in mind we have everything what we need to write a function:
<?php
function file_toggler(string $file, array $lineNumbers)
{
// normalize because file() starts with 0 and
// a regular user would use (1) as the first number
$lineNumbers = array_map(function ($number) {
return $number - 1;
}, $lineNumbers);
// get all lines and trim them because
// file() keeps newlines inside each line
$lines = array_map('trim', file($file));
// now we can take the line numbers and
// check if it starts with a comment.
foreach ($lineNumbers as $lineNumber) {
$line = trim($lines[$lineNumber]);
if (substr($line, 0, 2) == '//') {
$line = substr($line, 2);
} else {
$line = '//' . $line;
}
// replace the lines with the toggled value
$lines[$lineNumber] = $line;
}
// finally we write the lines to the file
// I'm using implode() which will append a "\n" to every
// entry inside the array and return it as a string.
file_put_contents($file, implode(PHP_EOL, $lines));
}
toggleFileComments(__DIR__ . '/file1.php', [3, 4]);
Hope it helps :-)
Upvotes: 2