Replace string in text file using PHP

前端 未结 3 1227
耶瑟儿~
耶瑟儿~ 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:20

    Thanks to your comments. I've made a function that give an error message when it happens:

    /**
     * Replaces a string in a file
     *
     * @param string $FilePath
     * @param string $OldText text to be replaced
     * @param string $NewText new text
     * @return array $Result status (success | error) & message (file exist, file permissions)
     */
    function replace_in_file($FilePath, $OldText, $NewText)
    {
        $Result = array('status' => 'error', 'message' => '');
        if(file_exists($FilePath)===TRUE)
        {
            if(is_writeable($FilePath))
            {
                try
                {
                    $FileContent = file_get_contents($FilePath);
                    $FileContent = str_replace($OldText, $NewText, $FileContent);
                    if(file_put_contents($FilePath, $FileContent) > 0)
                    {
                        $Result["status"] = 'success';
                    }
                    else
                    {
                       $Result["message"] = 'Error while writing file';
                    }
                }
                catch(Exception $e)
                {
                    $Result["message"] = 'Error : '.$e;
                }
            }
            else
            {
                $Result["message"] = 'File '.$FilePath.' is not writable !';
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' does not exist !';
        }
        return $Result;
    }
    
    0 讨论(0)
  • 2020-11-29 03:26

    Does this work:

    $msgid = $_GET['msgid'];
    
    $oldMessage = '';
    
    $deletedFormat = '';
    
    //read the entire string
    $str=file_get_contents('msghistory.txt');
    
    //replace something in the file string - this is a VERY simple example
    $str=str_replace($oldMessage, $deletedFormat,$str);
    
    //write the entire string
    file_put_contents('msghistory.txt', $str);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题