Page 1 of 1

Creating a single line string from multiple lines

Posted: Mon Feb 25, 2008 12:32 pm
by cczernia
I am trying to insert some text from an external source using php in a javascript variable.

Code: Select all

 
<?php
$text = " <p>Some text here</p>
 
<p>Some more text here</p>";
?>
 
<script>
var mystring = "<?php echo trim ($text); ?>";
</script
The problem is that the text I'm getting has returns in it and I keep getting a javascript error. I tried trimming the text but it only helped a little. Is there a way in php to get a string on a single line with no returns?

Re: Creating a single line string from multiple lines

Posted: Mon Feb 25, 2008 12:34 pm
by yacahuma
what is the external source?
what is the purpose of the script?

Re: Creating a single line string from multiple lines

Posted: Mon Feb 25, 2008 12:42 pm
by cczernia
I'm trying to create an iframe in javascript. Here is the actual javascript function.

Code: Select all

window.onload = function () {
    var val = '<?php echo trim (TEXT_INFORMATION); ?>';
        var testFrame = document.getElementById("myFrame");
        var doc = testFrame.contentDocument;
        if (doc == undefined || doc == null)
            doc = testFrame.contentWindow.document;
        doc.open();
        doc.write(val);
        doc.close();       
}
It works fine it the text is like this:

Code: Select all

<p>Some text here</p><p>Some more text here</p>
I get errors is the text is like this:

Code: Select all

<p>Some text here</p>
 
<p>Some more text here</p>

Re: Creating a single line string from multiple lines

Posted: Mon Feb 25, 2008 12:48 pm
by robble
Hi cczernia

Sounds like you need something like str_replace().

This will go through a string and replaces all occurences of a string with another. So you would search for a new line which would probably be "\r\n" or just "\n" and you would replace this with nothing - to simply remove the new lines.

If its a body of html, you could preserve the new lines as html line breaks (thereby getting rid of the 'real' new lines and also displaying it correctly). You would need to use nl2br() (new line to br).

For the two examples you would have:

Code: Select all

 
<?php
 
//this will remove all new lines
$text = str_replace("\r\n","",$text);
 
//this will change all new lines to line breaks (html)
$text = nl2br($text);
 
?>
 
I think nl2br() will remove all existing new lines (eg "\r\n") and replace with "<br />" but if it doesnt just run the str_replace function after calling nl2br()


**EDIT
After seeing your example code you do not need nl2br as you use paragraphs and already have your formatting set up.