【问题标题】:Replace carriage return in an email替换电子邮件中的回车符
【发布时间】:2012-07-28 05:37:50
【问题描述】:

我正在尝试用 PHP 中的换行符替换回车,这样我的网站版主就不必在每次输入来自我网站的电子邮件时添加新行时都输入
。我尝试了几种不同的方法来替换换行符,但都没有奏效。我尝试过的方法是:

preg_replace('/\r\n?/', "<br />", $str);
eregi_replace(char(13), "<br />", $str);
str_replace("\r\n", "<br />", $str);
str_replace("\n", "<br />", $str);

还有 nl2br 函数。

我在 Google 上寻找了大约半小时的答案,但没有找到任何结果。有人可以帮忙吗?

【问题讨论】:

  • nl2br 应该可以工作的,一定还有其他问题。
  • 您是刚刚写了这些行还是将 $str 也设置为等于它? $str = str_replace("\n", "
    ", $str);或 $str = nl2br($str);
  • 我是这样写的:$str = str_replace("\n", "
    ", $str);
  • ereg_*eregi_* 函数已弃用。不要使用它们!

标签: php html xhtml


【解决方案1】:

你是这样测试的吗?

$str = str_replace( "\r\n", "<br />", $str );
$str = str_replace( "\r", "<br />", $str );
$str = str_replace( "\n", "<br />", $str );

这应该总是有效的。请记住始终使用"\r" 而不是'\r'

【讨论】:

  • 小心,你可能会在这里用两个 &lt;br /&gt; 标记替换 Windows 行尾 "\r\n"
  • 谢谢,修改了脚本,先检查双打。
【解决方案2】:

来自 php.net documentation 的很好的例子

// Order of replacement
$str     = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';

// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);

【讨论】:

    【解决方案3】:

    您的正则表达式正在转义您的rn

    代替

    preg_replace('/\r\n?/', "<br />", $str);
    

    试试这个:

    preg_replace('/\\r\\n/', "<br />", $str);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2016-03-30
      • 2014-03-01
      相关资源
      最近更新 更多