将数据写入文件会在行尾添加^ M

使用PHP我使用fwrite将内容写入.htaccess文件,这一切都正常工作,但是当我在Vim中查看.htaccess后,它会在每行添加的末尾显示^ 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上本地工作

你的换行符是\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