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.
Thanks
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.
Thanks
2020 - Google brought me here for something similar.
Building on answer from user @Va1iant above
Environment:
Problem :
Solution:
<?= isset($_POST['MailingAddress']) ? stripcslashes(misc::esc($_POST['MailingAddress'])) : misc::esc($data['current_mailing_address']) ; ?>
where misc::esc -> return htmlspecialchars($var, ENT_QUOTES|ENT_HTML5, 'UTF-8');
Note :
I did not experiment with white-space: pre-line; as outlined at CSS Tricks so that could be a solution too - without using stripcslashes.
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.use nl2br(). The nl2br convert \n to <br /> as string .but <br />(string) not create New line. you should repalce <br />(string) to <br> then this will work.
example:
$content = "foo \n bar";
echo str_replace("<br />","<br>",nl2br($content));
result:
foo
bar
split by line:
function SplitLine($txt){
$txt = nl2br($txt);
$txt = explode("<br />",$txt);
return $txt;
}
I sent
foo
bar
with textarea as POST method to php.
print_r(SplitLine($_POST['text_area']));
result:
Array ( [0] => foo [1] => bar)
you can use for loop to get data and print it:
$result = SplitLine($_POST['text_area']);
for($i = 0;$i < count($result);$i++){
echo $result[$i]."<br>";
}
and result is
foo
bar
full code (Only For TEST):
<?php
//MyFunction
function SplitLine($txt){
$txt = nl2br($txt);
$txt = explode("<br />",$txt);
for($i = 0;$i < count($txt);$i++){
echo $txt[$i]."<br>";
}
return $txt;
}
//My Code
if(isset($_POST['submit_data'])){
print_r(SplitLine($_POST['text_area']));
}
?>
<br>
<form method='post'>
<textarea name='text_area'></textarea>
<br>
<input type='submit' value='Send Data :)' name='submit_data' />
</form>
I had a similar issue and the solution to mine was double-escaping the newline character. \\n