简体   繁体   English

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

[英]How do I eliminate line break from fgets function in PHP?

I am attempting to make a gallery that calls the image names from a flat file database using the PHP 'fgets' function.我正在尝试制作一个使用 PHP 'fgets' 函数从平面文件数据库中调用图像名称的图库。 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.一切正常,除了一个按钮。

I have one button on the page that is supposed to reset all the galleries to their default images using Javascript OnClick.我在页面上有一个按钮,应该使用 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。

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)”来解决这个问题,但我需要让它抓取整行,以便如果客户决定输入一个具有更长名称的文件,它不会破坏它们的图库。

Use rtrim() .使用rtrim()

Specifically:具体来说:

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

(To avoid trimming other characters, pass in just newline.) (为了避免修剪其他字符,只需传入换行符。)

Your best bet is to use the php trim() function.最好的办法是使用 php trim() 函数。 See http://php.net/manual/en/function.trim.phphttp://php.net/manual/en/function.trim.php

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM