You read the whole sidebar.html in the $text variable at the beginning of the script using something like:
$text = file_get_contents("sidebar.html");
So then the $text variable has all code of sidebar.html file.
The $newCode variable has the new string you want to use.
You work in memory with the $text, $codeToReplace and $newCode variables, making the replacement.
To save the updated text into the sidebar.html file, you open the file for writing, thus truncating it, and save the updated content into it, like this for example:
$fh = fopen("sidebar.html","w");
if ($fh){
fwrite($fh,$text);
fclose($fh);
}
Your script needs to have writing permission to overwrite the sidebar.html file.
Regards,
Veronica