php - replace string occurrences

后端 未结 3 641
-上瘾入骨i
-上瘾入骨i 2020-12-31 10:34

I have a string \"First line | second line | third line\" How can I replace | with a new line character?

I\'m trying to use

相关标签:
3条回答
  • 2020-12-31 11:00

    Use this:

    str_replace('|', PHP_EOL, $str);
    

    You should use PHP_EOL instead of "\n" because PHP_EOL will always work on all server platforms. (NB. Windows uses "\r\n" and unix/linux uses "\n").

    0 讨论(0)
  • 2020-12-31 11:07

    here it is

    str_replace('|',"\n",$string);
    

    when \n is placed in double qouted string it changes to a new line

    0 讨论(0)
  • 2020-12-31 11:09

    Using strtr is a tad faster than str_replace or preg_replace.

    echo strtr($string,'|', "\n");
    

    Mind the double quotes around the \n.

    Also, if you want to output HTML, a newline char is not sufficient, you need to replace it with <br /> tags.

    echo str_replace("|", "<br />\n", $string);
    
    0 讨论(0)
提交回复
热议问题