PHP的nl2br不工作(也不是替代品)

时间:2011-07-19 00:10:55

标签: php html email

我正在撰写联系表格。联系人消息可以包含换行符。他们需要转换为<br>。什么都行不通。这是我的测试代码:

mail( $email_to, $email_subject,

      '<html><head><title>' . $email_subject . '</title></head><body>'
    . $text_before_message
    . str_replace( array("\\r\\n","\\r","\\n"), "<br />", stripslashes($email_body) )
    . str_replace( array("\r\n","\r","\n"), "<br />", stripslashes($email_body) )
    . nl2br( stripslashes($email_body) )
    . str_replace( array('\\r\\n','\\r','\\n'), "<br />", stripslashes($email_body) )
    . str_replace( array('\r\n','\r','\n'), "<br />", stripslashes($email_body) )
    . stripslashes( nl2br($email_body) )
    . nl2br($email_body)
    . $text_after_message
    . '</body></html>'

    , 'MIME-Version: 1.0' . "\r\n"
    . 'Content-type: text/html; charset=UTF-8' . "\r\n"
    . 'From: ' . $email_from . "\r\n"
    . 'To: ' . $email_to . "\r\n"    
);

进入时:

Test.

Test.

电子邮件中的结果是(由于测试而重复多次):

Test.Test.

如果查看源代码,则会使用常规换行符(而不是<br>)。

为什么PHP会这样对我?这个问题似乎被问了很多,但我能找到的解决方案......没有任何区别。

如何将换行符转换为html符号?

3 个答案:

答案 0 :(得分:2)

快速回答:使用nl2br()。

换句话说,它对我有用。我用你的代码作为前缀:

$email_to="...me...";
$email_from=$email_to;
$email_subject="HTML test";

$text_before_message='<div style="color:red">BEFORE</div>';
$text_after_message='<div style="color:red">AFTER</div>';
$email_body=<<<EOD
1
2

3


4 (after two blank lines)
EOD;

至少在Thunderbird中,我看到一个行间距正确的文本邮件(对于nl2br()版本)。当我以HTML格式查看时,我也看到了正确的间距,以及顶部和底部的红色文字。

您可能正在使用不理解&lt; br /&gt;的电子邮件客户端,并希望查看&lt; br&gt;?!指定一个明确的doctype可能有所帮助(但谷歌建议它不会这样做。)

调试提示:当应该工作的所有内容都没有时,请手动检查它是否有效。即包含使用静态HTML块的测试,该块使用&lt; br /&gt; (和&lt; br&gt;)并查看它是否有效。如果它不是你知道“我使用哪个PHP函数”是错误的问题。

答案 1 :(得分:0)

在str_replace函数中使用双反斜杠对我有用。

http://php.net/manual/en/language.types.string.php 要指定文字单引号,请使用反斜杠()对其进行转义。要指定文字反斜杠,请将其加倍(\)。反斜杠的所有其他实例将被视为文字反斜杠:这意味着您可能习惯使用的其他转义序列(如\ r或\ n)将按字母顺序输出,而不是具有任何特殊含义。

答案 2 :(得分:-1)

为什么这么容易让它变得如此简单?

//here is the pull from the form
$your_form_text = $_POST['your_form_text'];

//line 1 fixes the line breaks - line 2 the slashes
$your_form_text = nl2br($your_form_text);
$your_form_text = stripslashes($your_form_text);

//email away
$message = "Comments: $your_form_text";
mail("destination_email@whatever.com", "Website Form Submission", $message, $headers);

您显然需要标题,可能还有更多字段,但这是您的文本区域。

相关问题