Reputation: 267059
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?
Upvotes: 1
Views: 321
Reputation: 6139
If there is only one $config['url'], use a preg_replace() http://us.php.net/preg_replace
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.
Upvotes: 0
Reputation: 3707
$filename = "/path/to/file/filename";
$configFile = file($filename);
$configFile[3] = '$'."config['url'] = '...could be anything here';";
file_put_contents($filename ,$configFile);
Upvotes: 0
Reputation: 15872
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);
Upvotes: 6
Reputation: 12323
$myline = "my confg line";
$file = "config.php";
$contents = file($file);
$contents[3] = $myLine;
$file = implode("\n", $contents);
Upvotes: 2
Reputation: 53851
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";
Upvotes: 1
Reputation: 42350
you could read the file, use str_replace or preg_replace on the appropriate strings, then write the file back to itself.
Upvotes: 0