2011-01-26 24 views
2

使用PHP我正在使用fwrite將內容寫入.htaccess文件,這一切都可以正常工作,但是當我在Vim中查看.htaccess之後,它會在每個文件末尾顯示^ M已添加的行。這似乎沒有引起任何問題,但我不確定發生了什麼事情導致這一點,以及是否可以預防?將數據寫入文件在行尾添加^ M

這是PHP:

$replaceWith = "#SO redirect_301\n".trim($_POST['redirect_301'])."\n#EO redirect_301"; 
    $filename = SITE_ROOT.'/public_html/.htaccess'; 
    $handle = fopen($filename,'r'); 
    $contents = fread($handle, filesize($filename)); 
    fclose($handle); 
    if (preg_match('/#SO redirect_301(.*?)#EO redirect_301/si', $contents, $regs)){ 
    $result = $regs[0]; 
    } 
    $newcontents = str_replace($result,$replaceWith,$contents); 
    $filename = SITE_ROOT.'/public_html/.htaccess'; 
    $handle = fopen($filename,'w'); 
    if (fwrite($handle, $newcontents) === FALSE) { 
    } 
    fclose($handle); 

,當我在Vim的檢查之後,我會看到這樣的事情:

#SO redirect_301 
Redirect 301 /from1 http://www.domain.com/to1^M 
Redirect 301 /from2 http://www.domain.com/to2^M 
Redirect 301 /from3 http://www.domain.com/to3 
#EO redirect_301 

服務器運行的是CentOS的,我在Mac上本地工作

+1

str_replace函數( 「\ r」, 「」,$ _ POST [ 'redirect_301']); – 2011-01-26 12:32:02

回答

3

你的換行符爲\r\n,而不是\n

之前寫入文件,你應該更換輸入無效:

$input = trim($_POST['redirect_301']); 
$input = preg_replace('/\r\n/', "\n", $input); // DOS style newlines 
$input = preg_replace('/\r/', "\n", $input);  // Mac newlines for nostalgia 
+0

OS X像其他UNIX一樣使用`\ n`,它是OS 9及更早版本使用`\ r` – Quentin 2011-01-26 12:35:08