PHP: fread 和换行符
PHP: fread and the newline character
如果我制作一个简单的文本文件,如下所示:
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 变量的回显正如预期的那样 "blank"。
我假设它接受并存储换行符。但是,如果我附加以下代码:
if ($third_word === '\n'){
echo "Third word is newline character.";
}
else {
echo "Third word is not newline character.";
}
(或者,== 而不是 ===)
然后结果是假的;测试 $newline_char = '\n';然而,在这样的 if 语句中,它工作正常。这里发生了什么?,是否存储了换行符?
===
运算符检查 value 和 type。
$x === $y
Returns 如果 $x 等于 $y 并且它们属于同一类型则为真
I assume it takes in and stores the new line character.
你的假设是正确的。
根据您创建文件的方式,它将是 \n
(在 Unix 上,OS X)或 \r\n
(Windows)。
确保检查您的编辑器的行结束字符。
What is happening here?
您的 if 计算结果为 false,因为 '\n'
的意思是 字面意思是一个反斜杠和一个 n
字符。
使用双引号获取换行符:"\n"
并且您的 if should 计算为 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
) 的二进制表示。
如果我制作一个简单的文本文件,如下所示:
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 变量的回显正如预期的那样 "blank"。 我假设它接受并存储换行符。但是,如果我附加以下代码:
if ($third_word === '\n'){
echo "Third word is newline character.";
}
else {
echo "Third word is not newline character.";
}
(或者,== 而不是 ===) 然后结果是假的;测试 $newline_char = '\n';然而,在这样的 if 语句中,它工作正常。这里发生了什么?,是否存储了换行符?
===
运算符检查 value 和 type。
$x === $y
Returns 如果 $x 等于 $y 并且它们属于同一类型则为真
I assume it takes in and stores the new line character.
你的假设是正确的。
根据您创建文件的方式,它将是 \n
(在 Unix 上,OS X)或 \r\n
(Windows)。
确保检查您的编辑器的行结束字符。
What is happening here?
您的 if 计算结果为 false,因为 '\n'
的意思是 字面意思是一个反斜杠和一个 n
字符。
使用双引号获取换行符:"\n"
并且您的 if should 计算为 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
) 的二进制表示。