I'm quite new to this, and have borrowed some code from another post I found, I don't know if what I am trying to do is the right or the best way, its just how I am "getting" it to work..
This is the code
<?php
$yn = $_POST['YN'];
echo $yn;
$fl='config.php';
/*read operation ->*/ $tmp = fopen($fl, "r"); $content=fread($tmp,filesize($fl)); fclose($tmp);
// here goes your update
$content = preg_replace('/\$yourname = \"(.*?)\";/', '$yourname = ""$YN"";', $content);
/*write operation ->*/ $tmp =fopen($fl, "w"); fwrite($tmp, $content); fclose($tmp);
?>
I am trying to update a config file entry that matches $yourname with the POST result, I can echo $yn and it contains the correct value, but I can't get the variable to work in the regex replace,
$content = preg_replace('/\$yourname = \"(.*?)\";/', '$yourname = ""$yn"";', $content);
so if $yn = karl then im trying to update $yourname = "" in the file to $yourname = "karl"
but I can't get it to work, the closest I get is it updating the file with the variable as text, ie $yourname = "$yn".
hope someone can help
I would suggest using a pattern like this
preg_replace( '/'.preg_quote( $yourname ).'\s*=\s*\"[^\"]+\";/', $yourname.'="'.$yn.'";', $content);
..'\s*=\s*\"([^\"]+)\";
In this case ( because it uses double quotes ), it's (prudent?) better to use concatenation and save the headache of escaping it. No need to be fancy
when simplicity will win the day.
Also be wary of mistakes like this $yn
vs $YN
in php variable names are case sensitive, without that knowledge it can be a major challenge to find the error, because to us humans it looks the same. Of course it doesn't help that file names, class names, functions and methods are case insensitive ( on Windows ). Really not sure if class and method names are case sensitive on linux, I try to avoid the issue and always use the same casing.
Seeing as it looks like the OP possibly wanted $yourname
( literally ) I updated the regx
preg_replace( '/\$yourname\s*=\s*\"[^\"]+\";/', '$yourname="'.$yn.'";', $content);
Using what you posted I managed to get it working, thank you so much :)
$content = preg_replace( '/\$yourname = \"(.*?)\";/', '$yourname = "'.$yn.'";', $content);