Search code examples
phpline-endings

convert ending line of a file with a php script


I'd like to know if it's possible to convert the endings lines mac (CR : \r) to windows (CRLF : \r\n) with a php script.

Indeed I've got a php script which run periodically on my computer to upload some files on a FTP server and the ending lines need to be changed before the upload. It's easy to do it manually but I would like to do it automatically.


Solution

  • In the end the safer way is to change what you don't want replaced first, here my function :

    /**Convert the ending-lines CR et LF in CRLF.
     * 
     * @param string $filename Name of the file
     * @return boolean "true" if the conversion proceed without error and else "false".
     */
    function normalize ($filename) {
                    
        echo "Convert the ending-lines of $filename into CRLF ending-lines...";
        
        //Load the content of the file into a string
        $file_contents = @file_get_contents($filename);
        
        if (!file_contents) {
            echo "Could not convert the ending-lines : impossible to load the file.PHP_EOL";
            return false;
        }
        
        //Replace all the CRLF ending-lines by something uncommon 
        $DontReplaceThisString = "\r\n";
        $specialString = "!£#!Dont_wanna_replace_that!#£!";
        $string = str_replace($DontReplaceThisString, $specialString, $file_contents);
                     
        //Convert the CR ending-lines into CRLF ones
        $file_contents = str_replace("\r", "\r\n", $file_contents);
                    
        //Replace all the CRLF ending-lines by something uncommon
        $file_contents = str_replace($DontReplaceThisString, $specialString, $file_contents); 
                    
        //Convert the LF ending-lines into CRLF ones
        $file_contents = str_replace("\n", "\r\n", $file_contents);
                    
        //Restore the CRLF ending-lines
        $file_contents = str_replace($specialString, $DontReplaceThisString, $file_contents);
        
        //Update the file contents
        file_put_contents($filename, $file_contents);
        
        echo "Ending-lines of the file converted.PHP_EOL";
        return true;
     }