如何从 PHP 变量中删除不需要的换行符/换行符?
当我通过 javascript 将 php 变量注册到 html 表单元素时,出现错误。就像如果在我的代码中有 php 变量 $edu_notes
并且我将此变量的值分配给一个 html 表单元素,
<textarea name="1_1_50" id="1_1_50" ></textarea>
即我的 Javascript 代码是:
document.getElementById('1_1_50').value = "<?php echo $edu_notes; ?>";
$edu_notes
的值来自 linkedin 配置文件,它是:
"First Text Line
Second Text Line"
第一个文本行和第二个文本行之间有一个空白行。 javascript 给出了一个错误,即
unterminated string literal
"First Text line
由于空行,Javascript 没有获取完整的字符串值。我尝试过一些 php 函数,例如 filter_var(),nl2br(),trim()
但没有解决这个问题。我还尝试通过 (string) $edu_notes
进行类型转换。
在我的源文件中,我得到的内容请参见下面的屏幕截图:
我正在执行此类功能,因为所有表单元素动态地来自数据库。
I am getting an error while i am registering php variable to html form element through javascript. Like If In my code there is php variable $edu_notes
and i am assigning this variable's value to a html form element that is
<textarea name="1_1_50" id="1_1_50" ></textarea>
and My Javascript code is :
document.getElementById('1_1_50').value = "<?php echo $edu_notes; ?>";
the value of $edu_notes
comes from linkedin profile which is :
"First Text Line
Second Text Line"
there is a gap of blank line between its first text line and second text line.
And the javascript gives an error that is
unterminated string literal
"First Text line
Javascript is not getting the full value as a string because of blank line. I have tried some php functions like filter_var(),nl2br(),trim()
but not resolving this issue. I have also tried to type cast through (string) $edu_notes
.
In my source file what i am getting please see screenshot below :
I am doing this type of functionality because all the form elements are coming from database dynamicaly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
使用 JS 友好的返回值替换字符串中的所有换行符。
Try
Which will replace any newlines in the string with JS-friendly returns.
这是因为它需要设置在同一行。在 PHP 中,用文字
\n
替换换行符,它应该可以正常工作。如果是单行文本框,请将换行符替换为空格。或者
It's because it needs to be set on the same line. In PHP, replace the newline character with the literal
\n
and it should work fine. If it's a single line textbox, replace newline with a space.or
尝试在 javascript 中使用多行字符串构造。
例如。
要在 php 代码中重新创建此内容,请将新行替换为 '\' 和新行 :-
to
这可以在 php 中使用 preg_replace 完成:-
希望这会有所帮助。
Try using the multi-line string construct in javascript.
Eg.
To re-create this in your php code, replace the new lines with a '\' and a new line :-
to
This can be done in php using preg_replace :-
Hope this helps.