使用php脚本转换文件的结束行

bas*_*ank 3 php line-endings

我想知道是否可以使用php脚本将结束行mac(CR:\ r)转换为windows(CRLF:\ r \n).

事实上,我有一个PHP脚本,它会在我的计算机上定期运行,以便在FTP服务器上上传一些文件,并且在上传之前需要更改结束行.手动操作很容易,但我想自动完成.

Jas*_*rke 5

你可以使用如下的简单正则表达式吗?

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

它可能不是最优雅或最快的解决方案,但它应该工作得很好(即它不会弄乱字符串中的现有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
Run Code Online (Sandbox Code Playgroud)