Str_replace in a string of HTML code

Greetings!
Long time off and on user of PHP, but not a ‘master coder’ by any means.
I want to read an html file with file_get_contents (which works fine) into a variable and then use str_replace to replace a string. Apparently php is sensitive to some characters in the HTML code and causes the str_replace to not work. Example:
$dest = “http://localhost/”;
$page = ($_REQUEST[‘page’]);
$pagepath = $dest.$page; // the full path to the html page
$username = ($_REQUEST[‘username’]); //the username is passed
$doc = file_get_contents($pagepath); // the html page is read into doc (This works fine)
str_replace("%%USERNAME%%",$password,$doc);
exit($doc);
This should return the page with the %%USERNAME%% replaced with the $username, but no change to $doc seems to be made.

What is the best/recommend way to do a ‘find/replace’ in an html file?
Have fun,
Paxton

You must use the returned value from str_replace - PHP: str_replace - Manual

Don’t use $_REQUEST. Use the correct $_POST, $_GET, or $_COOKIE variable that you expect data in.

Don’t put unnecessary () around things.

Don’t copy variables to other variables for nothing. Use the original variables.

You should trim, then validate all input data before using it. If data is valid, use it. If it is ‘required’ and it is not valid, that’s an error. You should set up a message letting the user know what is wrong with the data and how to correct it, and not execute any of the code that’s dependent on the existence of the data.

Greetings!
Thank you, phdr for your kind reply.
Somehow I missed the return value construct. In another language, the main string is modified in situ and there is no return.
That solved my problem.
I appreciate your other pointers as well although aware of most.
Have fun!
Paxton

Sponsor our Newsletter | Privacy Policy | Terms of Service