Search code examples
javascriptphpstr-replaceline-breaks

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. It seems to me that line breaks are coded as "/n"

When I retrieve the data I can display it on the screen correctly by using the following php lines

$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.

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.

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?

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:

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


Solution

  • 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