tags:

views:

203

answers:

3

I need to read through an Apache httpd.conf file, and find the following line:

#LoadModule blah blah

and uncomment it, i.e., replace it with

LoadModule blah blah

The catch here is that since the conf file can vary, there is a real possibility that the LoadModule line has already been uncommented.

There is also a possibility that the line simply isn't there, in this case my script has to add such a line to it at the end of the conf file.

Any idea how to write this in PHP?

+2  A: 

Try this:

preg_replace('/^#(LoadModule blah blah)/m', '$1', $str)

If blah blah should be variable, replace it by “.+”.

Gumbo
+1  A: 
$line  = "LoadModule blah blah";
$input = "your config file";
$count = 0;
$limit = 1;  // replace first occurrence only, change to -1 to replace all

$output = preg_replace("/^#?(?=\Q$line\E)/m", "", $input, $limit, $count);

if ($count == 0) $output = $output."\n$line";
Tomalak
+1  A: 
<?php
$found = false;
$f = fopen('apache.conf', 'r+');

while($line = fgets($f)) {
    if(preg_match("/^(#*)(\s*)LoadModule\s+blah.*/", $line)) {
        $found = true;
        if(substr($line, 0, 1) == '#') {
            fputs($f, preg_replace("/^(#+)(\s*)/", "", $line));
        }
        break;
    }
}

if(!$found) {
    fputs($f, "LoadModule blah blah\n");
}

fclose($f);
?>
Can Berk Güder