代码之家  ›  专栏  ›  技术社区  ›  Beehive

新行转义需要如何格式化才能正确显示消息

  •  -1
  • Beehive  · 技术社区  · 7 年前

    $msg 变量在显示器上,我的目标是用新行正确打印格式。我不确定我能做什么不同的事。另一方面,我可能会把这条信息写错。

    $msg ="Hey ".$row['emailName']."\rYou recently signed up to receive email updates from us, and we wanted to verify your email address.\nIf you signed  up to receive updates please press the confirmation link below:\nwww.domain.com/validateemail?email=".$row['emailAddress']."&emailID=".$row['emailID']."&emailed=1\nThe request came from".$row['signupIP']."\nIf you did not make this request, you can ignore this email\n \r Thanks,\rKathleen Williams\rHead Trainer";
    

    问题是它没有显示换行符。

    2 回复  |  直到 7 年前
        1
  •  1
  •   axiac    7 年前

    代码中的问题:

    • \r 不是新线; \n
    • www.domain.com/validateemail?... 不是URL。URL以协议开头( http:// https:// 等等)。没有它,电子邮件客户端不会将其检测为URL,也不会从中创建链接。

    有几种方法可以编写代码,使其易于阅读和修改。例如,您可以使用 heredoc syntax 对于字符串。它允许您在多行上书写文本,而无需担心如何书写换行符。此外,PHP parses it for variables 和转义序列的处理方式相同 double quoted strings

    // The text starting after the line `<<< END` and ending before 
    // the marker provided after `<<<` is a string.
    // It is stored into the $msg variable.
    $textBody = <<< END_TEXT
    Hey {$row['emailName']}
    You recently signed up to receive email updates from us, and we wanted to verify your email address.
    If you signed  up to receive updates please press the confirmation link below:
    
        http://www.example.com/validateemail?email={$row['emailAddress']}&emailID={$row['emailID']}&emailed=1
    
    The request came from {$row['signupIP']}.
    If you did not make this request, you can ignore this email.
    
    Thanks,
    Kathleen Williams
    Head Trainer
    
    END_TEXT;
    

    如果您想发送HTML电子邮件,可以使用相同的技术生成电子邮件正文,但不要忘记HTML不关心源代码中的换行符。将文本换行 <p> HTML元素生成段落并使用 <br> HTML元素强制在段落内换行。

    代码可以是这样的:

    $htmlBody = <<< END_HTML
    <p>Hey {$row['emailName']}</p>
    <p>You recently signed up to receive email updates from us,
    and we wanted to verify your email address.<br>
    If you signed  up to receive updates please press this 
    <a href="http://www.example.com/validateemail?email={$row['emailAddress']}&amp;emailID={$row['emailID']}&amp;emailed=1">confirmation link</a>.</p>
    
    <p>The request came from {$row['signupIP']}.<br>
    If you did not make this request, you can ignore this email.</p>
    
    <p>Thanks,<br>
    Kathleen Williams<br>
    Head Trainer</p>
    
    END_HTML;
    
        2
  •  1
  •   Neodan    7 年前

    不同的操作系统使用不同的符号表示行尾(EOL):

    • \r\n
    • \n -LF(Unix和OS X)
    • \r

    如果在HTML中打印此消息,则必须将EOL符号更改为 <br>

    您可以使用 nl2br 用于转换。