3

这应该是相当简单的。假设我有以下代码:

$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 

我究竟做错了什么?这可能是非常非常简单的事情......所以我道歉。

4

2 回答 2

6

您可能正在使用 Windows End-of-line 样式。

这是\r\n,不只是\n

尝试更换两者。

或者,不要指定任何字符列表(第二个参数)。通过指定\n你说只有修剪\n

trim($output)

请参阅此处的文档:http: //www.w3schools.com/php/func_string_trim.asp#gsc.tab=0


编辑(来自您的评论):

如果 trim() 不起作用,请尝试将您的字符串更改为字节数组并准确检查字符串末尾的字符。这让我怀疑还有其他一些不可打印的字符干扰。

$byteArray = unpack('C*', $output);
var_dump($byteArray);

http://www.asciitable.com/

于 2013-04-03T05:00:45.503 回答
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 .
于 2013-04-03T05:10:05.550 回答