简体   繁体   English

从PHP中将换行符添加到javascript中

[英]adding line break into javascript from php

Please bear with me as this is not easy to explain. 请忍受,因为这不容易解释。 I have a field in a MySQL database that was put there from a form with a textarea input. 我在MySQL数据库中有一个字段,该字段从带有textarea输入的表单放在那里。 It seems to me that line breaks are coded as "/n" 在我看来,换行符编码为“ / n”

When I retrieve the data I can display it on the screen correctly by using the following php lines 当我检索数据时,可以使用以下php行将其正确显示在屏幕上

$main_article1 = str_replace("\n", "<br />", $row[main_article]);
echo $mainarticle1;

However, now comes the tricky bit. 但是,现在有点棘手了。 I then want to insert that text into a scroller that uses Javascript. 然后,我想将该文本插入使用Javascript的滚动器中。

The code in that script is: 该脚本中的代码是:

var pausecontent=new Array()

pausecontent[0]='<?php echo $main_article1;?>'

I just get a blank screen. 我只得到一个黑屏。

If I remove the line breaks from the text in the database all works well - the main_article text appears in the scroller as it should - it only stops working when the line breaks are there. 如果我从数据库中的文本中删除了换行符,那么一切都将正常工作-main_article文本将按原样出现在滚动条中-仅在有换行符时才停止工作。

Does anyone know how I can get the line breaks in the database field to go through the PHP script and appear in the scroller text in the Javascript? 有谁知道如何在数据库字段中获得换行符以通过PHP脚本并出现在Javascript的滚动文本中?

I have also tried: 我也尝试过:

$main_article1 = str_replace("/n>", "%0D%0A", $row[main_article]);

but that does not work either 但这也不起作用

I hope I have made sense of what I am trying to do. 我希望我已经知道我要做什么。

Many thanks in advance. 提前谢谢了。

Tog 火车

Here is an update 这是更新

$main_article = 'This is a test<br />This is a test'

the code generated by php within the JS should be: JS内php生成的代码应为:

pausecontent[0]='This is a test<br />This is a test'

(all greyed out) but what I am getting is: (全部变灰),但我得到的是:

pausecontent[0]='This is a test
This is a test'

and the line break in the JS code is causing it to fail because the text is no longer greyed out after the line break 并且JS代码中的换行符导致它失败,因为换行符后文本不再变为灰色

You can try the nl2br() function 您可以尝试使用nl2br()函数

$main_article1 = nl2br($row[main_article]);

also I suggest leaving a space between your code and the closing php tag ( ?> ) 我也建议您在代码和结束php标记( ?> )之间留一个空格

pausecontent[0]='<?php echo $main_article1; ?>'

Got it at last, after too many days headache! 经过几天的头痛,终于知道了!

I was looking at the wrong replacement theories 我看错了替换理论

The answer is to use the following line: 答案是使用以下行:

$main_article1 = preg_replace("/\r\n|\r|\n/",'<br/>',$row[main_article]);

Now it works perfectly. 现在,它可以完美运行了。

Thanks to all for your help. 感谢大家的帮助。

Regards 问候

Tog 火车

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

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