javascript 如何消除 PHP 中 fgets 函数的换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7478250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I eliminate line break from fgets function in PHP?
提问by Shreger
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)”来解决这个问题,但我需要让它抓取整行,以便如果客户决定输入一个具有更长名称的文件,它不会破坏它们的图库。
回答by Ariel
Use rtrim()
.
使用rtrim()
.
Specifically:
具体来说:
rtrim($var, "\r\n");
(To avoid trimming other characters, pass in just newline.)
(为了避免修剪其他字符,只需传入换行符。)
回答by Alex Kennberg
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));
回答by Korvin Szanto
$b = fgets($a);
$b = preg_replace("/[\n|\r]/",'',$b);