PHP replace string after using file_get_contents

做~自己de王妃 提交于 2019-12-04 05:22:17

问题


Hi I am looking to replace words in an html email I am loading via file_get_contents

Here is my code:

<?

$message = file_get_contents("http://www.MYwebsiteExample.com/EmailConfirmation.php");


$message =  preg_replace('/SAD/', "HAPPY", $message);
// Also tried this below and it does not work either
 $message = str_replace('/SAD/', "HAPPY", $message);

?>

I am hoping to find all the patters of SAD (case sensitive) and replace them with HAPPY. For some reason if I use file_get_contents it doesn't seem to be working.

Thanks

UPDATE: Jan 22, 2013

Actually, sorry Correction when I add the $ it does not work. Its not necessary for my code. I can do a work around but this does not work below:

$message = str_replace("$SAD", "HAPPY", $message); /// does not work. Not sure why
$message = str_replace("SAD", "HAPPY", $message); /// without the $ it does work.

回答1:


$message = str_replace("$SAD", "HAPPY", $message);

needs to be:

$message = str_replace('$SAD', "HAPPY", $message);

Otherwise PHP will interpret it as the variable $SAD. See this post for an explanation on the difference between single and double quotes.




回答2:


You shouldn't use regular expressions for this; it's simple string replacement:

$message = strtr($message, array(
    '$SAD' => 'HAPPY',
));

Btw, if you use "$SAD" for the search string, PHP will try to evaluate a variable called $SAD, which doesn't exist and will throw a notice if your error_reporting is configured to show it.



来源:https://stackoverflow.com/questions/14466090/php-replace-string-after-using-file-get-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!