Home > Enterprise >  Unwanted result by exploding a string and adding p tags
Unwanted result by exploding a string and adding p tags

Time:01-27

here is a text made in notepad

lorem ipsum
dolor sit

lorem ipsum
dolor sit

I stored the text inside a mysql table
column type - text
collation - utf8mb4_croatian_ci

getting the text I need to add some tags, like this:

$blocks = explode("\n\n", $str);  // $str is the text  
$res = '';
foreach($blocks as $block){
    $block = str_replace("\n", "<br>\n", $block);
    $block = "<p>" . $block . "</p>";
    $res .= $block . "\n\n";
}
echo $res;

I'm expecting following:

<p>lorem ipsum<br>
dolor sit</p>

<p>lorem ipsum<br>
dolor sit</p>

Instead of the above I'm getting the following:

<p>lorem ipsum<br>
dolor sit<br>
<br>
lorem ipsum<br>
dolor sit</p>

So I need firstly to explode the given string by double new lines
and then - inside the each block - replace single new lines by <br>
and finally cover each block with <p></p>

Btw earlier I worked on this table and with the same php code - and it worked
Today, suddenly - I'm getting the unwanted result

I tried to change end of lines from crlf to lf and vice versa - without success

update

what I see now:

if the string is defined by php - it works

if the string is made by a textarea or contenteditable div - it works

if the string is copy-paste from notepad to a cell table - it gives the above - unwanted result

so I think - something is problem with end of lines

CodePudding user response:

As mentionned in the comments, it's probably a whitespace character issue. If your text isn't supposed to contain anything else than spacings and newlines, you probably should remove all others first (mostly \r and \t).

A simple regexp could do the trick :

$cleaned_string = preg_replace('/[\r\t]*/m', '', $string);
  • Related