<?php
$info = "Hi";
$file = fopen("file.txt","w");
fwrite($file,$info);
fclose($file);
?>
I am currently using the code above to write a value into a text file. However, is it possible to retrieve certain variables that are stored within that text file and just rewrite them instead?
Example:
file.txt
$one = "first";
$two = "second";
$three = "third";
Through PHP code, a specified "variable" in the text file should have its contents changed.
New file.txt
$one = "first";
$two = "hi";
$three = "third";
If I understand you correctly, you have some PHP code written in a file, file.txt. If you have only stored variables, I believe you can get away with some regular expression to do what you want.
Nevertheless, for anything more complex (maybe even for this specific case), I would recommend that you use some PHP parser to parse all the variables and their values, and make your changes accordingly. (here's a PHP parser written in PHP).
EDIT:
Just to clear things up, a simple replacement will not suffice. Imagine you have something like $first = "a";
, and then you decide to replace a
, with \
. A naive replacement, would leave you with $first = "\";
in your file.txt file.
yes, you can use str_replace() to replace the variables with the data you like
$s_input = 'this is a #first text';
$a_repfr = array('#first', '#second', '#third');
$a_repto = array('funny', 'php', 'love');
$s_output = str_replace($a_repfr, $a_repto, $s_input);