tags:

views:

129

answers:

6

I have a file called config.php, I want it to remain exactly as is, however on Line # 4 there is a line saying:

$config['url'] = '...could be anything here';

I'd like to only replace the contents of line # 4 with my own url provided for $config['ur'], is there a way to do this in PHP?

A: 

you could read the file, use str_replace or preg_replace on the appropriate strings, then write the file back to itself.

GSto
+1  A: 

Either create another config (myconfig.php). Include the original and overwrite the option. include myconfig.php instead of the original one.

OR

Go to where config is included (you did use a single place for all your includes right?) and set the config option there.

   include "config.php"
   $config['url'] = "my_leet_urlz";
Byron Whitlock
+2  A: 
$myline = "my confg line";

$file = "config.php";

$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);
code_burgar
+5  A: 

Since you know the exact line number, probably the most accurate way to do this is to use file(), which returns an array of lines:

$contents = file('config.php');
$contents[3] = '$config[\'url\'] = "whateva"'."\n";
$outfile = fopen('config.php','w');
fwrite($outfile,implode('',$contents));
fclose($outfile);
Lucas Oman
A: 
$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename  ,$configFile);
ChronoFish
A: 

If there is only one $config['url'], use a preg_replace() http://us.php.net/preg%5Freplace

something like: $pattern = '\$config['url'] = "[\d\w\s]*"' $file_contents = preg_replace($pattern, $config['url'] = "my_leet_urlz";,$file_contents);

you'll need to fix the pattern as I'm new at regex and I know that's not right.

easement