Php keep the returns!

he all you clever lot, I’ve got a little system that you edit the text in a free text box and it adds to a mysql db, the output however removes the returns, carage returns, ideally I would like these to not only be retained but output as <p></p> any ideas? cheers;)

thanks people, and should this action only be put on the output, echo?

There have been userland variations on nl2br - search for [google]php nl2p[/google] to see what others have done with varying degrees of success.

Just out of personal preference I keep the brackets next to the function call with no space so:

echo nl2p($myrow[‘text’]);

This also looks loads neater when doing thinks like this:

echo “Hello " . nl2p($name) . " how are you today.”;

However like I said you might want to strip tags:
echo strip_tags(nl2p($variable));

Its worth noting that php will execute innermost function first.
Stripping the tags will keep the output secure.

You might also want to have an outputting function so you can centralize where you make the changes in future so:

function html_output($variable) {
  $variable = strip_tags(nl2p($variable));
  return $variable;

echo html_output($variable);

^yup again :smiley:

(as in - yes thats the right way to call it!)

cheers jkingston, if I use this code should I do the below:

echo $myrow[‘text’];

to this

echo nl2p ($myrow[‘text’]);

:cool::wink: just getting used to how php calls so prob got this totally wrong lol

This should be a simpler solution, you might want to strip all tags before putting the string through this function.

function nl2p($string) {
  $stringA = explode("\
  $newString = '';
  foreach($stringA as $stringI) {
    $newString .= '<p>'.$stringI.'</p>';
  return $newString;

cool thanks for your help here everyone, I’ll give it a go now, thanks :wink:


It does not actually removes the returns carriage regurns but they don’t directly outputted in the webpage as new lines. So you need to use nl2br to look the output as entered. But to have them along with <p> tags there is function user notes in nl2br manual page which seems quite enough:

function nl2p($string, $class='') { 
        $class_attr = ($class!='') ? ' class="'.$class.'"' : ''; 
            .preg_replace('#(<br\\s*?/?>\\s*?){2,}#', '</p>'."\
".'<p'.$class_attr.'>', nl2br($string, true)) 

And yes indeed it is to be done when you echo the string. To preserve the new lines in your database, use textarea in your form.