Replace carriage return in an email

2019-08-08 23:52发布

I'm trying to replace carriage returns with a line break in PHP so that my site moderators don't have to type
every time they want to add a new line when typing an email from my site. I've tried several different methods to replace the line breaks but none have worked. The methods that I have tried are:

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

and the nl2br function.

I've looked for the answer on Google for about half an hour and haven't found anything. Can anyone help?

标签: php html xhtml
3条回答
冷血范
2楼-- · 2019-08-09 00:28

Your regular expression is escaping your r and n.

Instead of

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

Try this:

preg_replace('/\\r\\n/', "<br />", $str);
查看更多
放我归山
3楼-- · 2019-08-09 00:38

Quite good example from 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);
查看更多
Animai°情兽
4楼-- · 2019-08-09 00:39

Did you test it like this?

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

This should work pretty much always. And remember always use "\r" instead of '\r'.

查看更多
登录 后发表回答