How do you create a new line in a textarea when inserting the text via PHP?
I thought it was \n
but that gets literally printed in the textarea.
How do you create a new line in a textarea when inserting the text via PHP?
I thought it was \n
but that gets literally printed in the textarea.
Without seeing your code I cannot be sure, but my guess is you are using single quotes ('\n') instead of double quotes ("\n").
PHP will only evaluate escape sequences if the string is enclosed in double quotes. If you use '\n', PHP will just take that as a literal string. If you use "\n", PHP will parse the string for variables and escape sequences and print a new line like you are expecting.
Try
$text = 'text line one' . PHP_EOL . 'text line two';
echo '<textarea>' . $text . '</textarea>';
Will add each text on reparate line in texarea.
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']);
What Alay Geleynse said was right, I had the same problem as you and the issue was due to the escape characters (\r, \n) was there. To 'unescaped' the variable I used $var = stripcslashes($var)
and it's shown correctly
Just to complete the solution for that issue, as others mentioned use "\n"
*(or in some cases "\r\n"
) instead of '\n'
And when you want to show the textarea contents using php and keeping new lines, you need to use nl2br
, so if you assing a varialbe for your text and call it $YOUR_TEXT , you should use that function as: nl2br($YOUR_TEXT)
More details could be found here
\n
, while Windows and Windows programs usually need \r\n
.I had a similar issue and the solution to mine was double-escaping the newline character. \\n
//Some Additional Related Validation
function test_input_hacks($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = strip_tags($data);
return $data;
}
$message = test_input_hacks($_POST['message']);
//For All Operating Systems
echo str_replace(array("\r\n", "\r", "\n"),'<br>', $message);
$row['content']=stripslashes($row['content']);
$row['content']=str_replace('<br />',"newline",$row['content']);
$row['content']=htmlentities($row['content']);
$row['content']=str_replace('newline',"<br>",$row['content']);
Use like this for dynamically enter each line you can use
echo chr(13)
© 2022 - 2024 — McMap. All rights reserved.
echo '\n';
instead ofecho "\n";
. – Certaintystr_replace('\n', "\n", $contact->address)
which is retarded. Why is that? – Subsistenceadd_slashes
? Save to a database? – Freely\t
). – Renter\n
, are you typing it as two distinct characters, or pressing the enter key? More precisely, what's the origin of your data? – Certainty