nl2br
nl2br(string $string, bool $use_xhtml = true): string
在字符串中每个换行符(\n)前插入 HTML 换行标记(默认 <br />,XHTML 风格);不做 HTML 转义。
C C23
#include <stdio.h>
int main(void) {
const char *s = "line one\nline two\nend";
for (const char *p = s; *p != '\0'; p++) {
if (*p == '\n') {
printf("<br />\n"); // 与 nl2br 一致:在每个换行符前插入 br
} else {
putchar(*p);
}
}
printf("\n");
return 0;
}
line one<br /> line two<br /> end
C++ C++26
#include <iostream>
#include <string>
int main() {
std::string s = "line one\nline two\nend";
std::string out;
for (char ch : s) {
if (ch == '\n') {
out += "<br />\n"; // 与 nl2br 一致:在每个换行符前插入 br
} else {
out += ch;
}
}
std::cout << out << "\n";
return 0;
}
line one<br /> line two<br /> end
C# v11.0.100
string text = "line one\nline two\nend";
Console.WriteLine(text.Replace("\n", "<br />\n")); // 纯替换,不做 HTML 转义
line one<br /> line two<br /> end
Go v1.27.4
package main
import (
"fmt"
"strings"
)
func main() {
text := "line one\nline two\nend"
fmt.Println(strings.ReplaceAll(text, "\n", "<br />\n")) // html/template 会自动转义
}
line one<br /> line two<br /> end
Java v27.0.1
public class Main {
public static void main(String[] args) {
String text = "line one\nline two\nend";
System.out.println(text.replace("\n", "<br />\n")); // replaceAll 走正则:得写 "\\n"
}
}
line one<br /> line two<br /> end
JavaScript v26.13.1
const text = "line one\nline two\nend";
console.log(text.replaceAll("\n", "<br />\n")); // 文本不可信时先做 HTML 转义再替换
line one<br /> line two<br /> end
PHP v8.6.0
echo nl2br("line one\nline two\nend"); // <br /> 插在每个 \n 之前;第二参数 false 得 <br>
line one<br /> line two<br /> end
Python v3.15.2
text = "line one\nline two\nend"
print(text.replace("\n", "<br />\n")) # 纯替换,不做 HTML 转义
line one<br /> line two<br /> end
Rust v1.99.1
fn main() {
let text = "line one\nline two\nend";
println!("{}", text.replace("\n", "<br />\n")); // str::replace,不做 HTML 转义
}
line one<br /> line two<br /> end
TypeScript v26.13.1
const text: string = "line one\nline two\nend";
console.log(text.replaceAll("\n", "<br />\n")); // 文本不可信时先做 HTML 转义再替换
line one<br /> line two<br /> end
语言差异说明
C:手写逐字符拷贝插入,同样不转义。
C++:手写逐字符拷贝插入,同样不转义。
C#:内置 replace 做简单的 \n → <br />\n 替换,同样不转义。
Go:内置 replace;html/template 对所有插值自动转义(想保留 <br /> 需要 template.HTML 类型标记),text/template 则不转义。
Java:内置 replace;Java EE/JSP 模板引擎默认转义逻辑同理。
JavaScript:用 replaceAll;XSS 语境是本条目的重点——替换结果若进 innerHTML 就是经典 XSS 注入点——不可信文本先做 HTML 实体转义(& < > " ')再插 br,或干脆不用 innerHTML(textContent + CSS white-space: pre-line 让浏览器自己把 \n 渲染成换行,零注入面);"文本先行转义、br 最后插入"是通用安全顺序。
PHP:核心语义:nl2br 是"插入"而非"替换"——<br /> 加在每个 \n 之前,换行符本身保留(所以 HTML 源码里既有 br 又有换行,<pre> 或纯文本场景不丢换行);默认 XHTML 风格 <br />,第二参数传 false 得 <br>;默认不转义 HTML:不可信文本必须先 htmlspecialchars($s, ENT_QUOTES) 再 nl2br(),顺序反了 <script> 已被注入;换行规范化:Windows 的 \r\n 会被插成 <br />\r\n,展示前先 str_replace("\r\n", "\n") 归一。
Python:内置 replace 做简单的 \n → <br />\n 替换,同样不转义;Django/Jinja2 模板引擎默认转义同理。
Rust:内置 replace;askama 等模板引擎默认转义同理。
TypeScript:同 JS,replaceAll。