2013-08-22 23 views
3

我想知道是否可以使用php腳本將結尾行的mac(CR:\ r)轉換爲windows(CRLF:\ r \ n)。用php腳本轉換文件的結尾行

確實我有一個php腳本,它定期在我的電腦上運行,以便在FTP服務器上傳一些文件,在上傳之前需要更改結束行。手動操作很容易,但我想自動完成。

+0

'str_replace函數(陣列( 「\ r \ n」 個, 「\ n」 個),陣列( 「\ n」, 「\ r \ n」 個) )'? – PeeHaa

回答

0

到底安全的方法是改變你不想先被替換,我在這裏的功能:

/**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; 
} 
2

文件加載基本上爲一個字符串,並調用是這樣的:

function normalize($s) { 
    // Normalize line endings 
    // Convert all line-endings to UNIX format 
    $s = str_replace(array("\r", "\n"), "\r\n", $s); 
    // Don't allow out-of-control blank lines 
    $s = preg_replace("/\r\n{2,}/", "\r\n\r\n", $s); 
    return $s; 
} 

這是here片段,最後regeg可能需要一些進一步的擺弄。

編輯:固定的邏輯刪除重複的替換。

+0

我認爲邏輯有點有缺陷;如果用'\ r \ n'替換所有的'\ n',那麼用'\ r \ n'替換所有的'\ r',示例字符串'Hello \ n'會變成'Hello \ r \ n \ n'。然後,你就可以繞過這個你不需要的正則表達式。 –

+0

@JasonLarke:我已經爲此添加了一個修復程序,現在應該可以工作。請注意這是一個概念性指南,而不是最終產品:P – hexblot

5

你可以使用簡單的正則表達式嗎?

function normalize_line_endings($string) { 
return preg_replace("/(?<=[^\r]|^)\n/", "\r\n", $string); 
} 

它可能不是最優雅的或最快的解決方案,但它應該工作得很好(即它不會弄亂現有的Windows(CRLF)行結束的字符串)。

說明

(?<=  - Start of a lookaround (behind) 
    [^\r] - Match any character that is not a Carriage Return (\r) 
    |  - OR 
^ - Match the beginning of the string (in order to capture newlines at the start of a string 
)  - End of the lookaround 
\n  - Match a literal LineFeed (\n) character 
0

我測試,但有一些錯誤:看來,而不是替換CR結束行來增加一個CRLF結束行,這裏的功能,我微微它修改避免打開文件這一功能外:

​​
1

刪除所有\ r字符然後用\ r \ n替換\ n可能會更容易。

這將需要的所有變化的護理:

$output = str_replace("\n", "\r\n", str_replace("\r", '', $input)); 
相關問題