Jump to content

Writing to PHP variables within a file


x1nick

Recommended Posts

I seem to remember this being possible, but can't remember how its done

 

Got a config file with a bunch of variables

 

EG:

#Define array

$cfg = array();

#Site name

$cfg['site_name'] = 'eg.com';

#Project code

$cfg['project_cdoe'] = 'EGW001';

 

$site = 'This is a example';

 

 

How can I update these variables using PHP code?

I know I could use fwrite to basically write everything in a file but is there a way to update single variables easily

Link to comment
https://forums.phpfreaks.com/topic/208029-writing-to-php-variables-within-a-file/
Share on other sites

function write_value_of($var,$oldval,$newval)
{
$contents = file_get_contents('myfile.php');
$regex = '~\\'.$var.'\s+=\s+\''.$oldval.'\';~is';
$contents = preg_replace($regex, "$var = '$newval';", $contents);
file_put_contents('myfile.php', $contents);
}

 

usage:

write_value_of('$site',"This is a example",'Text to replace');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.