简体   繁体   中英

PHP - replace all “\n” Occurrences in a string

I am getting a string in my PHP output with lots of \\n characters which I would like to convert into <p> to get a new line characters in html outpot.

I have tried following:

strtr($myString, "\n", "<p>");    
string_replace ("\n", "<p>", $myString);

Both of these doesn't seems to work. Any ideas what's wrong in the syntax?

I think you should use nl2br($myString);

http://www.php.net/manual/fr/function.nl2br.php

<?
   $string = "Ceci\r\nest\n\rune\nchaîne\r";
   echo nl2br($string);

  /* will output
  Ceci<br />
  est<br />
  une<br />
  chaîne<br /> //*/
?>

Try this:

PHP:

<?php

$myString = 'Hello\nWorld';

echo '<p>'. implode('</p><p>', explode('\n', $myString)) .'</p>';

?>

Output:

<p>Hello</p><p>World</p>

您想要nl2br

<?php $new_string = nl2br($myString); echo $new_string; ?>

The function you are trying to do called srt_replace() .

Anyway, what good it will do to replace \\n with <p> ?

If you want it to be with linebreaks just use [nl2br()][1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM