PHP 是否在读取文本文件时删除了 CR?

Is PHP removing CR when reading text file?

某个txt文件只包含CRLF换行符。已通过在启用 "Show All Characters" 的 Notepad++ 中打开文件来确认。

使用PHP读取文件时,使用file_get_contents(),或fopen(),CR字符似乎被过滤掉了:

<?php
    ...
    $fh = fopen($path, 'r');

    while (!feof($fh)) {
        $string .= fread($fh, 1024);
    }

    preg_match_all('/\r/', $string, $matches);
    var_dump($matches);

    // 0 matches: array(1) { [0]=> array(0) { } }

    $string2 = file_get_contents($path);
    preg_match_all('/\r/', $string2, $matches2);
    var_dump($matches2);

    // 0 matches: array(1) { [0]=> array(0) { } }
?>

我很困惑,因为每个提到的函数的文档都没有说明这一点。也许还有其他方法可以按照文件的存储方式打开文件。

需要确认这些函数是否过滤掉或"normalize" CR 字符。是这样,这些功能可能还有什么"normalizing"?有没有办法避免这种行为?

更明确地说,当我将文件加载到我的变量中时,我需要这些 CR 字符和每一位都保持完整。

谢谢

试试这个解决方案:

preg_match_all('/'.PHP_EOL.'/', $string, $matches);

PHP_EOL作为跨平台方式的换行符,所以处理Windows/Mac/Unix.

同时检查 documentation 这个常量。

是的,这就是 fopen 根据您提供的参数所做的,您可以在文档中找到它:http://php.net/manual/en/function.fopen.php

Windows offers a text-mode translation flag ('t') which will transparently translate \n to \r\n when working with the file. In contrast, you can also use 'b' to force binary mode, which will not translate your data. To use these flags, specify either 'b' or 't' as the last character of the mode parameter.

即您可以通过在 mode 参数中使用 'b' 标志来避免这样的 "translation"。例如:

fopen($path, 'rb'); // Read in binary mode