0

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
Fractaliste
  • 5,777
  • 11
  • 42
  • 86
  • 9
    Use double-quotes instead: `substr_count($article->texte, "\n");` – Amal Murali Dec 11 '13 at 11:58
  • possible duplicate of [substr\_count not working with new lines?](http://stackoverflow.com/questions/10367971/substr-count-not-working-with-new-lines) – Imane Fateh Dec 11 '13 at 12:04
  • @AmalMurali Thanks a lot! Is this subtleties documented? Edit: find it http://uk.php.net/manual/en/language.types.string.php – Fractaliste Dec 11 '13 at 12:05
  • @Fractaliste: [Yes, it is](http://uk.php.net/manual/en/language.types.string.php#language.types.string.syntax.double). – Amal Murali Dec 11 '13 at 12:06

2 Answers2

1

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

gprusiiski
  • 430
  • 4
  • 18
1

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);
kguest
  • 3,804
  • 3
  • 29
  • 31
  • Can I use `PHP_EOL` in place of `"\n"` and `"\r"`? – Fractaliste Dec 11 '13 at 12:22
  • The value of PHP_EOL is platform specific, so it differs from, say Mac to Windows and the likes of Linux and really should only be used for when you are generating output, so in this scenario I wouldn't use it. – kguest Dec 11 '13 at 12:36