Replace string in text file using PHP

前端 未结 3 1240
耶瑟儿~
耶瑟儿~ 2020-11-29 02:52

I need to open a text file and replace a string. I need this

Old String: 
New String: 

        
3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 03:33

    This works like a charm, fast and accurate:

    function replace_string_in_file($filename, $string_to_replace, $replace_with){
        $content=file_get_contents($filename);
        $content_chunks=explode($string_to_replace, $content);
        $content=implode($replace_with, $content_chunks);
        file_put_contents($filename, $content);
    }
    

    Usage:

    $filename="users/data/letter.txt";
    $string_to_replace="US$";
    $replace_with="Yuan";
    replace_string_in_file($filename, $string_to_replace, $replace_with);
    

    // never forget about EXPLODE when it comes about string parsing // it's a powerful and fast tool

提交回复
热议问题