PHP怎么实现替换整个文件内容

有一个文件123.php,要用php怎么实现替换它里面的内容,是全部替换。
比如它现在里面的内容是 <?php 我是123 ?> 要把它替换成 <?php 我也是123 ?>

如何用PHP代码实现?

//简单写法(未考虑大文件,文件不存在的情况);

$content =file_get_contents('123.php');
//复杂替换可以考虑使用正则。
$content = str_replace('我是123','我也是123',$content);

file_put_contents('123.php',$content);追问

不考虑里面的内容怎么写? 里面的内容不一定是 我是123

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-07-09
function replace_text($search , $replace , $text){
        $content =file_get_contents($text);
        $res = str_replace($search,$replace,$content);
        file_put_contents($text,$res);
}


外部
$this->replace_text('hello', 'hi', '123.php');


如果是复杂的正则替换 把  str_replace 改成preg_replace ,
原理是这样需要过滤,优化操作自己添加

第2个回答  2013-10-11
$file = '123.php';
if (is_writable($file) == false) {
         die('不能写!');
}
$data = '<?php 我也是123 ?> ';
file_put_contents ($file, $data);

本回答被提问者和网友采纳