Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line breaks with <p> tags [duplicate]

Tags:

php

I've got a form with a textarea and I want to change the linebreaks from the input into paragraphs (using the <p> tag). I'm using explode and implode to replace \n with </p><p>, but if you have two line breaks in a row, you end up with </p><p></p><p>. I'm trying to use a foreach loop to go through each element and check if it it's empty to combat this, but it doesn't seem to be working at all. Here's what I have:

foreach($text as $value){
    if($value!=''){
        $newtext.='</p><p>'.$value;
    }
}

That still gives </p><p></p><p> for things that are double spaced. I also tried replacing if($value!='') with !is_null(trim($value)) and it still didn't work. What is wrong with my code, and how can I fix it?

like image 273
user2874270 Avatar asked Dec 11 '22 07:12

user2874270


1 Answers

Something like this will work:

$newtext = '<p>' . implode('</p><p>', array_filter(explode("\n", $textarea))) . '</p>';
  1. create array by splitting on linebreaks \n
  2. filter out empty elements
  3. join together with p tags
like image 54
AbraCadaver Avatar answered Dec 23 '22 06:12

AbraCadaver