gpt4 book ai didi

php - 如何用
替换换行符或\r\n?

转载 作者:IT老高 更新时间:2023-10-28 12:01:03 30 4
gpt4 key购买 nike

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

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

这些应该都可以,但我仍然得到换行符。它们是双重的:“\r\r”。这不应该让这些都失败,对吧?

最佳答案

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

示例(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);
?>

但如果它仍然不起作用,请确保文本 $desciption是双引号。

这是因为单引号不会“扩展”转义序列,例如 \n与双引号字符串相比。引用 PHP 文档:

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.

关于php - 如何用 <br/> 替换换行符或\r\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5946114/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com