PHP 用“不可见字符”替换字符串(\n)

发布于 2024-12-10 10:22:09 字数 391 浏览 0 评论 0原文

我从数据库得到这样的文本。

{br}{/br}hello!{br}{/br}

该文本在 textarea 元素内输出。

我需要的是将所有 '{br}{/br}' 替换为不可见的字符 '\n' ,它应该在文本区域本身中设置一个输入空间。希望:)

我试图做的是。

$text = str_replace('{br}','\n',$text);
        $text = str_replace('{/br}','\n',$text);

然后在文本区域中输出 $text ,但字符 \n 可见:|

i get from db a text like this.

{br}{/br}hello!{br}{/br}

this text is outputted inside a textarea element.

what i need is to replace all the '{br}{/br}' with invisible char '\n' which should set a enter space in the textarea itself. hoping :)

what i tryed to do is.

$text = str_replace('{br}','\n',$text);
        $text = str_replace('{/br}','\n',$text);

then output $text in textarea, but chars \n are visible :|

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挽清梦 2024-12-17 10:22:09

使用 str_replace 和双引号 "\n" 将其解释为换行符;带单引号的 '\n' 是一个反斜杠,后跟一个 n

$text = str_replace('{br}{/br}', "\n", $text);

我不知道为什么您要为 {br} 调用 str_replace 一次,为 {/br} 调用一次。您是否希望将每对 {br}{/br} 替换为两行新行?如果是这样,您可以通过一次调用更简单地完成此操作:

$text = str_replace('{br}{/br}', "\n\n", $text);

Use str_replace with a double quoted "\n" for it to be interpreted as a newline; '\n' with single quotes is a literal backslash followed by an n.

$text = str_replace('{br}{/br}', "\n", $text);

I'm not sure why you're calling str_replace once for {br} and once for {/br}. Do you want each pair of {br}{/br} to be replaced by two new lines? If so, you could do that more simply with a single call:

$text = str_replace('{br}{/br}', "\n\n", $text);
满栀 2024-12-17 10:22:09

您需要将 \n 放在双引号中,而不是单引号中。变量和转义序列不会插入单引号中。此外,您可能希望将整个字符串 {br}{/br} 替换为一个新行 - 根据您所做的操作,您将把它替换为两个新行。

所以:

$text = str_replace('{br}{/br}',"\n",$text);

可能就是你想要的。这可能值得您阅读,这样您就知道自己可以/可以做什么。与 PHP 中的字符串无关。

You need to put the \n in double quotes, not single quotes. Variables and escape sequences are not interpolated in single quotes. Also, you probably want to replace the whole string {br}{/br} with a single new line - with what you have done you will replace it with two.

So:

$text = str_replace('{br}{/br}',"\n",$text);

Is probably what you want. It's probably worth you reading this so you know what you can/can't do with strings in PHP.

ゞ花落谁相伴 2024-12-17 10:22:09

尝试使用双引号

$text = str_replace('{/br}', "\n", $text);

Try using double quotes

$text = str_replace('{/br}', "\n", $text);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文