简体   繁体   中英

PHP Script - Comment/Uncomment line

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?

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:

  • We want to manipulate a specific file (we need the filename)
  • We want to toggle specific line numbers inside this file (list of line numbers)
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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM