代码之家  ›  专栏  ›  技术社区  ›  Leo

PHP如何将\n转换为换行符

php
  •  0
  • Leo  · 技术社区  · 7 年前

    如何生成使用单引号声明的字符串 \n 好像是用双引号声明的?

    例如。

    echo 'Line1\nLine2'; // Does not split.
    echo "Line1\nLine2"; // It splits.
    
    $s = 'A string declared using \n single quotes which I can\'t change...';
    echo $s // I need this to have the split at \n
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   iainn    7 年前

    你应该能 str_replace 将它们转换为实际的新行:

    $s = str_replace('\n', "\n", $s);
    

    看到了吗 https://3v4l.org/j0etV

    如果要将其显示为HTML,请注意,还需要运行它 nl2br (或者,如果您使用的是模板引擎,这可能已经为您完成了)

        2
  •  2
  •   Jonathan Gagne    7 年前

    首先你得修理你的绳子。 放 \' ' , str_replace()

    $s = 'A string declared using \n single quotes which I can\'t change...';
    $s= str_replace('\n', "\n", $s);
    
        3
  •  0
  •   Hudson Cantuária    7 年前

    你能替换吗 \' 在里面 ' str_replace()

    $s = 'A string declared using \n single quotes which I can\'t change...';
    $s= str_replace('\n', "\n", $s);
    

    或使用以下语法

    nl2br($s);
    
    推荐文章