Passing newlines using PHP to a textarea - php

I'm trying to make a list of email addresses (each one on a new line). I pull the array from my database, explode it along the comma delimiter, and run it through a foreach loop.
$emailsList = "";
foreach($emails as $email)
{
$emailsList = $emailsList . "\n" . $email;
}
echo "Additional Report Emails<textarea name='showReportsEmails'>".$emailsList."</textarea>";
When I look in the textarea itself, it will literally show the line break tag in the textarea. What can I do to get rid of this and have the text behave as I want?
<br />
email1#gmail.com<br />
email2#gmail.com
Thanks!

It looks like when the result is printed in the textarea, the PHP new lines (\n) are converted to <br/>s. So, maybe there's a nl2br() function being used to output the result into the textarea. It should be fixed by removing that. Otherwise, you can use the code below when setting the textarea's content:
<textarea><?php echo implode("\n", array_map('trim', explode("\n", strip_tags($emailsList)))); ?></textarea>
The code above first removes all html tags from the $emailsList variable, and then also removes white spaces before and after lines, so you would be good to go with this.

You should be using Carriage returns instead of HTML code in the textarea.
\r

The name suggest the the element can only hold text. It doesn't parse as HTML rather it does so as text.
I tested this code:
<?php
$value = "Hello,\nname\nis\nScript47.";
echo "<textarea>$value</textarea>";
?>
Output
Edit 1:
You could also use \r to see if it helps.

Related

How to show line break using PHP?

I am inserting this text What is <br/> PHP? into the database
Now I want to show this text as a line break. Like below:
What is PHP?
I am using PHP nl2br() function but it's not working. I am getting the value like this:
What is <br/> PHP?
How can I solve it?
Thank You.
A question comes up here... where are you inserting this text (string) ?
If you are injecting it as HTML you'll get the desired result in the rendered page.
I assume this is not the case: you want HTML line breaks turned into newlines.
So...
nl2br()converts newlines into <br />: that's the opposite you want to do
http://php.net/manual/en/function.nl2br.php
Just use str_replace:
$out = str_replace( "<br/>", "\n", $in );
Where $in is the input string and $out is the desired output
http://php.net/manual/en/function.str-replace.php
Just a couple of things to note:
1) the above code will work with HTML line breaks <br/>, not if you have <br>, or <br />
If this is an issue you may pass the function array of strings and array of their replacements. This is well documented in the link above.
2) If you use the code snipped I wrote above you'll end having two spaces in the resulting string:
What is  (with trailing space)
 PHP (with leading space)
Just use css instead of server-side transformations:
p {
white-space: pre-line;
}
<p>I am inserting this text What is
PHP? into the database
</p>
<p>Now I want to show this text as a line break. Like below:</p>
<p>What is
PHP?</p>

How to retrieve text as typed in Mysql mediumtext field? [duplicate]

I know when saving a textarea you can use the nl2br() or str_replace to change the /n to br tags etc. However what im not sure about how to insert line breaks into a textarea. I cant seem to find much about putting the data back into a textarea with those line breaks.
For example I have a form where users can update fields. So the user may enter:
foo
bar
baz
When that is saved to the database it would be saved as:
foo<br />bar<br />baz<br />
Now when that user goes back to that form after a page refresh all the fields are automatically populated with their previous data by taking the data from the database.
However the textarea shows the br tags as text instead of adding in the line breaks. i also tried changing the br tags to /n hoping the textarea would interpret these as line breaks but no joy. As well as this I also tried escaping etc.
So my questions are can this be done? Or more importantly can it be done using HTML/PHP (im using smarty). If that isnt possible can it be done using javascript?
Examples would be appreciated.
thanks for reading
Don't do nl2br when you save it to the database. Do nl2br when you're displaying the text in HTML. I can strongly recommend to not store any HTML formatting in the database (unless you're using a rich HTML editor as well, in which case it would be silly not to).
A newline \n will just become a newline in the textarea.
You could use str_replace to replace the <br /> tags into end of line characters.
str_replace('<br />', PHP_EOL, $textarea);
Alternatively, you could save the data in the database without calling nl2br first. That way the line breaks would remain. When you display as HTML, call nl2br. An additional benefit of this approach is that it would require less storage space in your database as a line break is 1 character as opposed to "<br />" which is 6.
Ahh, it is really simple
just add
white-space:pre-wrap;
to your displaying element css
I mean if you are showing result using <p> then your css should be
p{
white-space:pre-wrap;
}
You can use following code:
$course_description = nl2br($_POST["course_description"]);
$course_description = trim($course_description);
Some wrong answers are posted here.
instead of replacing \n to <br />, they are replacing <br /> to \n
So here is a good answer to store <br /> in your mysql when you entered in textarea:
str_replace("\n", '<br />', $textarea);
My recommendation is to save the data to database with Line breaks instead parsing it with nl2br. You should use nl2br in output not input.
For your question, you can use php or javascript:
PHP:
str_replace('<br />', "\n", $textarea);
jQuery:
$('#myTextArea').val($('#myTextArea').val().replace(#<br />#, "\N"));
PHP Side: from Textarea string to PHP string
$newList = ereg_replace( "\n",'|', $_POST['theTextareaContents']);
PHP Side: PHP string back to TextArea string:
$list = str_replace('|', '
', $r['db_field_name']);
This works on me.
str_replace(array("\r", "\n"), '
', $textareavalue);
The simple way:
Use this to insert into mysql:
$msg = $_GET['msgtextarea']; //or POST and my msg field format: text
$msg = htmlspecialchars($msg, ENT_QUOTES);
And use this for output:
echo nl2br($br['msg']);
What I found works in the form is
str_replace('<br>', PHP_EOL, $textarea);
From PHP using single quotes for the line break worked for me to support the line breaks when I pass that var to an HTML text area value attribute
PHP
foreach ($videoUrls as $key => $value) {
$textAreaValue .= $value->video_url . '\n';
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTML/JS
$( document ).ready(function() {
var text = "<?= htmlspecialchars($textAreaValue); ?>";
document.getElementById("video_urls_textarea").value = text;
});
I'm not sure this is possible but you should try <pre><textarea> ... </textarea></pre>
<?php
$smarty = new Smarty;
$smarty->assign('test', "This is a \n Test");
$smarty->display('index.tpl');
?>
In index.tpl
{$test|nl2br}
In HTML
This is a<br />
test

Output data from MySQL to HTML on multiple rows, works in textare but not in <div>

If i generate HTML data from MySQL using PHP like this:
/* SQL query */
while ($result = mysql_fetch_object($sql_query) {
$text = $result->table_text;
}
If i echo the result to a textarea I get correct line breaks that the user has entered in a previous <form>. For example
Code:
<textarea>$text</textarea>
Result:
These
are
row breaks
But if I echo the result to a <div> everything comes out to one line.
Code:
<div>$text</div>
Result:
These are row breaks
If I run the query in command line, it seem's to output the row breaks. But how can I generate them in a div?
Use nl2br function
echo nl2br($text);
That is because "\n" or "\r\n" have no effect when directly displayed in a div tag.
You could:
use css to set the white-space property of that div to pre or something similar to achieve what you want.
wrap <pre> tags around the $text.
use first use PHP's nl2br() to convert the line characters to html tags.
The choice is yours.

PHP: trying to create a new line with "\n"

i'm writing this:
echo "foo";
echo "\n";
echo "bar";
and "bar" is not written in the line below.
What am i doing wrong?
Javi
Newlines in HTML are expressed through <br>, not through \n.
Using \n in PHP creates a newline in the source code, and HTML source code layout is unconnected to HTML screen layout.
If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL
echo "foo";
echo PHP_EOL ;
echo "bar";
In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.
ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.
foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;
If you want to write plain text, you must ensure the content type is set to Content-Type: text/plain. Example:
header('Content-Type: text/plain');
If you are dealing with HTML, you have two options. One is to inset a new line using <br> (Or <br /> for XHTML). The other is to put the plain text in a <pre> element (In this case "pre" stands for preformatted).
PHP generates HTML. You may want:
echo "foo";
echo "<br />\n";
echo "bar";
if your text has newlines, use nl2br php function:
<?php
$string = "foo"."\n"."bar";
echo nl2br($string);
?>
This should look good in browser
Assuming you're viewing the output in a web browser you have at least two options:
Surround your text block with <pre> statements
Change your \n to an HTML <br> tag (<br/> will also do)
Since it wasn't mentioned, you can also use the CSS white-space property
body{
white-space:pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "hello\nthere";
?>
</body>
Would display
hello
there
We can use \n as a new line in php.
Code Snippet :
<?php
echo"Fo\n";
echo"Pro";
?>
Output:
Fo
Pro
It will be written on a new line if you examine the source code of the page. If you want it to appear on a new line when it is rendered in the browser, you'll have use a <br /> tag instead.
This works perfectly for me...
echo nl2br("\n");
Reference: http://www.w3schools.com/php/func_string_nl2br.asp
Hope it helps :)
This answer was so obvious and it took me forever to figure out:
echo "foo
bar";
I know that looks like it's wrapping. It's not. What I did is I literally hit return halfway through the string, between foo and bar. It creates a new line in the HTML source and makes your PHP look horrible. This was in Linux/Apache.
echo "foo<br />bar";
We can apply \n in php by using two type
Using CSS
body {
white-space: pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "Fo\n Pro";
?>
</body>
Result:
Fo
Pro
Using nl2br
nl2br: Inserts HTML line breaks before all newlines in a string
<?php
echo nl2br("Fo.\nPro.");
?>
Result
Fo.
Pro.
the html element break line depend of it's white-space style property.
in the most of the elements the default white-space is auto, which mean break line when the text come to the width of the element.
if you want the text break by \n you have to give to the parent element the style:
white space: pre-line, which will read the \n and break the line, or
white-space: pre which will also read \t etc.
note: to write \n as break-line and not as a string , you have to use a double quoted string ("\n")
if you not wanna use a white space, you always welcome to use the HTML Element for break line, which is <br/>
$a = 'John' ; <br/>
$b = 'Doe' ; <br/>
$c = $a.$b"<br/>";

Problem printing PHP output on multiple lines

I am newbie to PHP I have written the following program:
$address=array('abc#gmail.com','abc#hotmail.com','def#yahoo.com');
foreach($address as $value)
{
echo "processing $value\n";
}
If you see I have \n in the echo statement but I am not getting the output on new line.
How can I get each output on a new line?
If you are outputting this as HTML then you must of course use a HTML break <br />.
If you're working in a browser, you need to break lines with
<br>
You need to print an HTML line break instead:
<br/>
Since you are printing to a browser
\n will line break properly when you view the source, but not in the HTML display. As mentioned, you need to use the <br/> node for HTML
You may want to wrap your output in a <pre> tag as your browser is expecting HTML and is just collapsing the whitespace. The pre tag will reflect the whitespace (\t \n etc);
Alternately you can use a break tag, or wrap the data in a block display element. (eg: <p> or <div>)

Categories