Friday, May 27, 2016

Comment a line after finding a string in file in php

Comment a line after finding a string in file in php:

I want to find a string in a file & comment the whole line in which that string is find out.

For this we have to use the following code:


            $path_to_root_file = "/path/of/file";
            $var = $this->getLineWithString($path_to_root_file, "find_string");
            $file_contents = file_get_contents($path_to_root_file);
            $file_contents = str_replace($var, "//$var", $file_contents);
            file_put_contents($path_to_root_file, $file_contents);

            function getLineWithString($fileName, $str) {
                $lines = file($fileName);
                foreach ($lines as $lineNumber => $line) {
                    if (strpos($line, $str) !== false) {
                        return $line;
                    }
                }
                return -1;
            }


Thanks

No comments:

Post a Comment