【问题标题】:PHP: fread and the newline characterPHP:fread 和换行符
【发布时间】:2018-03-10 19:17:26
【问题描述】:

如果我制作一个简单的文本文件,如下所示:

first line.
second line.

并通过以下方式应用 fread:

$fh = fopen("test_file_three.txt",'r') or die("Error attempting to 
open file.");
$first_word = fread($fh,5);
$second_word = fread($fh,6);
$third_word = fread($fh,1);
$fourth_word = fread($fh,3);
echo $first_word;
echo "<br />";
echo $second_word;
echo "<br />";
echo $third_word;
echo "<br />";
echo $fourth_word;
echo "<br />";

$third_word 变量的回声正如预期的那样只是“空白”。 我假设它接收并存储换行符。但是,如果我附加以下代码:

if ($third_word === '\n'){
    echo "Third word is newline character.";
}
else {
    echo "Third word is not newline character.";
}

(或者,== 而不是 ===) 然后结果是假的;测试 $newline_char = '\n';然而,在这样的 if 语句中,工作正常。这里发生了什么?是否存储了换行符?

【问题讨论】:

  • 可能不是\n 可能是\r 或只是`\`。而单引号代表文字串,不妨试试双引号。

标签: php newline fread


【解决方案1】:

我假设它接收并存储换行符。

你的假设是正确的。

根据您创建文件的方式,它将是 \n(在 Unix、OS X 上)或 \r\n(Windows)。

确保检查编辑器的行结束符。

这里发生了什么?

您的 if 计算结果为 false,因为 '\n' 表示字面上是一个反斜杠和一个 n 字符

使用双引号获取换行符:"\n" 并且您的 if 应该计算为 true

What is the difference between single-quoted and double-quoted strings in PHP?


我真的建议您使用 hexdump 函数,这样您就可以准确地知道字符串中存储的内容。

Here's an implementation of a hexdump function.

通过调用 hex_dump 而不是 echo 来调整您的代码:

hex_dump($first_word);
hex_dump($second_word);
hex_dump($third_word);
hex_dump($fourth_word);

给我以下内容:

 0 : 66 69 72 73 74 [first]
 0 : 20 6c 69 6e 65 2e [ line.]
 0 : 0a [.]
 0 : 73 65 63 [sec]

您可以看到$third_word 由单个字节0x0a 组成,这是换行符的二进制表示 (\n)。

【讨论】:

    【解决方案2】:

    PHP Comparison Operators

    === 运算符检查 valuetype

    $x === $y 如果 $x 等于 $y 并且它们属于同一类型,则返回 true

    【讨论】:

      猜你喜欢
      • 2014-02-17
      • 2012-10-24
      • 2017-12-14
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多