这应该是相当简单的。说我有以下代码:
$output = file_get_contents($random_name . ".txt");
echo "<pre>";
echo str_replace("\n", "\nN ", $output);
echo "</pre>";
$output
看起来像这样:
PDF Test File
N Congratulations, your computer is equipped with a PDF (Portable Document Format)
N reader! You should be able to view any of the PDF documents and forms available on
N our site. PDF forms are indicated by these icons:
N or.
N
N
让我们说我想通过以下方式摆脱这两个最后的换行符:
$outputTrimmed = trim($output, "\n");
我认为,那会输出:
PDF Test File
N Congratulations, your computer is equipped with a PDF (Portable Document Format)
N reader! You should be able to view any of the PDF documents and forms available on
N our site. PDF forms are indicated by these icons:
N or.
但相反,这段代码:
$output = file_get_contents($random_name . ".txt");
$outputTrimmed = trim($output, "\n");
echo "<pre>";
echo str_replace("\n", "\nN ", $outputTrimmed);
echo "</pre>";
结果:
PDF Test File
N Congratulations, your computer is equipped with a PDF (Portable Document Format)
N reader! You should be able to view any of the PDF documents and forms available on
N our site. PDF forms are indicated by these icons:
N or.
N
N
我做错了什么?它可能是真的,真的简单...所以我道歉。
答案 0 :(得分:6)
您可能正在使用Windows End-of-line样式。
哪个是\r\n
,而不仅仅是\n
。
尝试更换两者。
或者,不要指定任何charlist(第二个参数)。指定\n
即表示仅修剪\n
trim($output)
请参阅此处的文档:http://www.w3schools.com/php/func_string_trim.asp#gsc.tab=0
编辑(来自您的评论):
如果trim()不起作用,请尝试将字符串更改为字节数组并检查 完全 字符串末尾的字符。这让我怀疑还有其他一些不可打印的角色在干扰。
$byteArray = unpack('C*', $output);
var_dump($byteArray);
答案 1 :(得分:2)
试试这个
$output1 = file_get_contents($random_name . ".txt");
$output=str_replace("\n", "\nN ", $output1);
$outputTrimmed = trim($output,"\n");
echo "<pre>";
echo $outputTrimmed;
echo "<pre>";
输出
PDF Test File
N Congratulations, your computer is equipped with a PDF (Portable Document Format)
N reader! You should be able to view any of the PDF documents and forms available on
N our site. PDF forms are indicated by these icons:
N or .