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

标签 php line-endings

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

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

最佳答案

你可以只使用像下面这样的简单正则表达式吗?

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

关于php - 使用php脚本转换文件的结束行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18376167/

相关文章:

bash - 匹配以 grep 结尾的 unix 行

windows - 在 OS X 上运行时,如何提交具有 LF 行结尾的文件,但将某些文件类型保留在 CRLF 中?

git - 使用 .gitattributes 使 git 存储带有 CRLF 行结尾的文本文件

php - 只允许字母、数字、空格、逗号、句点的正则表达式?

php - 获取创建日期早于 14 天的行

php - 减少搜索结果中标题和描述之间的空间

file-io - 在 Clisp 中以二进制模式写入/读取文件

php - 在 SQL 查询中执行算术运算

php - 如何将时间戳变量转换为可读的现有脚本? (假如)

git - 为什么 .gitattributes 不会覆盖 Linux 上的 core.autocrlf 配置?