如何替换\r&amp; \\\<br/>与&lt; br /&gt ;? [英] How to replace \r &amp; \n with &lt;br/&gt;?

查看:114
本文介绍了如何替换\r&amp; \\\<br/>与&lt; br /&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图简单地替换一些新的行。尝试了3种不同的方法,我没有任何改变:

  $ description = preg_replace('/ \ r?\\\
| \r /','< br />',$ description);
$ description = str_replace(array(\r\\\
,\r,\\\
),< br />,$ description);
$ description = nl2br($ description);

这些应该都可以工作,但我仍然会换行。他们是双重的:\r\r。这应该不会使任何这些失败的权利?

解决方案

已经有 nl2br() 函数替换 插入 < br> 在换行符之前的标签:

示例( codepad ):

 <?php 
//不会工作
$ desc ='第一行\两行';
//应该工作
$ desc2 =第一行\在线两位;

echo nl2br($ desc);
echo'< br />';
echo nl2br($ desc2);
?>

但是,如果它仍然无效,请确保文本 $ desciption

这是因为单引号不会'扩展'转义序列,如 \\\
与双引号字符串进行比较。来自PHP文档的引用:


注意:与双引号和heredoc语法,变量和转义序列不同特殊字符出现在单引号字符串中时不会被展开。



Trying to simply replace some new lines. Have tried 3 different ways and I get no change:

$description = preg_replace('/\r?\n|\r/','<br/>', $description);
$description = str_replace(array("\r\n","\r","\n"),"<br/>", $description);
$description = nl2br($description);

These should all work but I still get the newlines. They are double: "\r\r". That shouldn't make any of these fail right?

解决方案

There is already nl2br() function that replaces inserts <br> tags before new line characters:

Example (codepad):

<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";

echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

But if it is still not working make sure the text $desciption is double-quoted.

That's because single quotes do not 'expand' escape sequences such as \n comparing to double quoted strings. Quote from PHP documentation:

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

这篇关于如何替换\r&amp; \\\<br/>与&lt; br /&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆