PHP - Form mail converting line breaks to spaces

喜夏-厌秋 提交于 2019-12-24 13:19:05

问题


I have a <textarea> in a form for user comments, and when the contents are passed to form mail, the line breaks are being converted to spaces. How can I preserve the line breaks that the form's user types in?

relevant php:

$comments = $_REQUEST['comments'];
// This grabs the comments from the submitted form

//...

$to = $configEmail;

$subject = "Website Order Received: $offer";

$contents = "blah blah blah...";
if (!empty ($comments)) {
    $contents = $contents."\nComments: $comments\n\n";
}

//...

mail($to, $subject, $contents);

And in the HTML end of the form... (the comments are put into the form if it's submitted with errors, so data isn't lost)

<label>Comments / Questions</label>
<textarea name="comments"><?php echo $comments; ?></textarea>

If I type:

line 1
line 2
line 3

It remains like that if the form is submitted with errors, so $comments = $_REQUEST['comments']; is definitely preserving the line breaks. But the plain-text e-mail gives me:

line 1 line 2 line 3

How can I preserve the line breaks?


回答1:


The problem is the line breaks coming from the textarea are \n not <br>.. So replace the \n by <br> before sending the mail..

$body= str_replace("[enter]", "\n",$body);

Rember user double quoutes in "\n"...




回答2:


Try the nl2br() function, if it doesn't initially work try to send the message as an HTML email.



来源:https://stackoverflow.com/questions/8717701/php-form-mail-converting-line-breaks-to-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!