为什么fgets在字符串末尾添加空格? [英] Why does fgets adds a space at the end of string?
问题描述
我有一个包含单个字符串的文件.我打开文件并使用fopen和fgets读取值,我注意到在字符串的末尾添加了一个空格.
I have a file which contains a single string. I open the file and read the value, with fopen and fgets, i noticed that a space is added at the end of the string.
$file = fopen("myfile", "r") or exit("<br><p>Unable to open file</p><br>");
$mystring= fgets($file);
fclose($file);
myfile的内容:
Content of myfile:
Hello
测试
echo "<p>'".$mystring."'</p>"; //Output: 'Hello '
您可以看到,即使文件中没有空格,字符串的结尾现在也有一个空格.
As you can see there is now a space at the end of the string, even though there is no space in the file.
我用linux命令"cat"尝试了相同的操作:
I tried the same with the linux command "cat":
$mystring = shell_exec("cat myfile");
echo "<p>'".$mystring."'</p>"; //Output: 'Hello '
在字符串末尾保留一个空格.
Still a space at the end of the string.
我的目标是将文件中的字符串与代码中的值进行比较.
My goal is to compare the string in the file, with a value in my code.
if ($mystring === "Hello")
{
echo "Equal";
}
else
{
echo "not equal";
}
我总是得到不平等".如何读取实际文件内容并将其存储到变量中?
I always get "not equal". How can i read and store the actual file content into my variable?
推荐答案
要调试字符串,请尝试以下操作:
To debug a string, try this:
foreach(str_split($mystring) as $chr) {
printf("[%02x] %s <br />",ord($chr),$chr);
}
根据您的情况,它应该产生类似...
This should, in your case, yield something like...
[48]高
[65] e
[6c] l
[6c] l
[6f] o
[0a]
[48] H
[65] e
[6c] l
[6c] l
[6f] o
[0a]
记下最后一个. 0x0a
是换行符,它是通过 fgets
和 shell_exec
获得的所有文本行的结尾,因为这是标记结束的地方行(两个函数都从各自的活动返回输出的行").
Take note of that last one. 0x0a
is a newline character, which is what all lines of text obtained through fgets
and shell_exec
end with, since that's what marks the end of the line (both functions return a "line" of output from their respective activity).
(注意:您可能会得到 [0c] [0a]
或CRLF,具体取决于您的系统.)
(Note: You may get [0c] [0a]
, or a CRLF, depending on your system.)
要解决此问题,只需在处理字符串之前对字符串使用 rtrim()
.
To fix, just use rtrim()
on the string before handling it.
由于您在注释中添加了允许使用'hello'
的大小写,因此可以使用更明确的名称,例如 rtrim($ mystring,"\ r \n);
Since you added in a comment that the case of 'hello '
should be allowed, then you can use something more explicit, like rtrim($mystring, "\r\n");
这篇关于为什么fgets在字符串末尾添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!