GitsD
GitsD

Reputation: 668

How to trim unwanted newlines/linebreaks from PHP variable?

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 :

enter image description here

I am doing this type of functionality because all the form elements are coming from database dynamicaly.

Upvotes: 1

Views: 1525

Answers (4)

CookieMonster
CookieMonster

Reputation: 1237

Try

  document.getElementById('1_1_50').value =   '<?php echo str_replace(array( "\r", "\n", "%0a", "%0d"), "' + \"\\r\\n \"  + '", $edu_notes); ?>'

Which will replace any newlines in the string with JS-friendly returns.

Upvotes: 2

Ajoy
Ajoy

Reputation: 230

Try using the multi-line string construct in javascript.

Eg.

  var myStr = "line one \
line two";

To re-create this in your php code, replace the new lines with a '\' and a new line :-

"First Text Line

Second Text Line"

to

"First Text Line \

Second Text Line"

This can be done in php using preg_replace :-

$edu_notes = preg_replace( '#\n#', '\\\n', $edu_notes );

Hope this helps.

Upvotes: 0

Tom Gullen
Tom Gullen

Reputation: 61739

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.

<?php echo str_replace("\n", " ", $edu_notes); ?>

or

<?php echo str_replace("\n", "\\n", $edu_notes); ?>

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359776

document.getElementById('1_1_50').value =
    '<?php echo str_replace("\n", "\\n", $edu_notes) ?>';

Upvotes: 1

Related Questions