如何消除PHP中fgets函数的换行符?

时间:2021-08-17 07:54:33

I am attempting to make a gallery that calls the image names from a flat file database using the PHP 'fgets' function. There are different sections in the gallery, each with it's own default image, and a small list of images that the users can select from. Everything is working fine, except for one button.

我正在尝试使用PHP'fgets'函数创建一个从平面文件数据库调用图像名称的库。图库中有不同的部分,每个部分都有自己的默认图像,以及用户可以选择的一小部分图像。一切都工作正常,除了一个按钮。

I have one button on the page that is supposed to reset all the galleries to their default images using Javascript OnClick. It works exactly as I want it to, with one small hitch: It copies the line break at the end of the line allong with the characters on the line, breaking the Javascript.

我在页面上有一个按钮,它应该使用Javascript OnClick将所有画廊重置为默认图像。它完全按照我想要的方式工作,有一个小故障:它将行尾的换行符复制到行上的字符,打破了Javascript。

The offending code:

违规代码:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';

//This should output the proper javascript, but does not
<?php
$a = fopen('c.txt','r');
if (!$a) {echo 'ERROR: Unable to open file.'; exit;}
$b = fgets($a);
echo "document.getElementById('i1').src='$b';";
fclose($a);
?>

}

How it outputs:

它如何输出:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';
document.getElementById('i1').src='00.jpg
';}

As you can see, the ending quotation mark and the semi-colon falls on the next line, and this breaks the button.

如您所见,结束引号和分号落在下一行,这会打破按钮。

With the files I'm using now, I can get around this problem by changing, "fgets($a)" to, "fgets($a, 7)" but I need to have it grab the entire line so that if the client decides to enter a file with a longer name, it does not break the gallery on them.

使用我现在使用的文件,我可以通过将“fgets($ a)”改为“fgets($ a,7)”来解决这个问题,但是我需要让它抓住整行,这样如果客户端决定输入名称较长的文件,它不会破坏它们的库。

3 个解决方案

#1


18  

Your best bet is to use the php trim() function. See http://php.net/manual/en/function.trim.php

你最好的选择是使用php trim()函数。见http://php.net/manual/en/function.trim.php

$b = trim(fgets($a));

#2


19  

Use rtrim().

使用rtrim()。

Specifically:

特别:

rtrim($var, "\r\n");

(To avid trimming other characters, pass in just newline.)

(为了修剪其他角色,请直接传递。)

#3


2  

$b = fgets($a);
$b = preg_replace("/[\n|\r]/",'',$b);

#1


18  

Your best bet is to use the php trim() function. See http://php.net/manual/en/function.trim.php

你最好的选择是使用php trim()函数。见http://php.net/manual/en/function.trim.php

$b = trim(fgets($a));

#2


19  

Use rtrim().

使用rtrim()。

Specifically:

特别:

rtrim($var, "\r\n");

(To avid trimming other characters, pass in just newline.)

(为了修剪其他角色,请直接传递。)

#3


2  

$b = fgets($a);
$b = preg_replace("/[\n|\r]/",'',$b);