Domanda

I use a textarea to write comments on my website. The comment is saved in a SQLite DB.

My problem is when I try to retrieve my comment from the DB in order to replace every carriage return with <p> tags (before showing it to the user).

I've first try the nl2br function and it works fine, plenty of <br/> appears on my code.

Then I've try :

substr_count($article->texte, '\n');
substr_count($article->texte, '\r');

But the return result is always 0. It surprises me because I thought nl2br would replace \n and \r chars.

Did I miss something ?

mb_detect_encoding($article->texte); //returns UTF8
È stato utile?

Soluzione

You need to understand that PHP interprets text inside single quotes literally, but expands what is inside double quotes; so you will get a different result if you do

substr_count($article->texte, "\n");

To answer your question, using nl2br is quickest, but if you really want to replace every occurrance of "\n" with "</p><p>" then do:

$content = str_replace("\n", '</p><p>', $content);

Altri suggerimenti

Expressions like \n and \r are evaluated only when in double quotes, so try "\n" and "\r"

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top