0

So I've created a post function, but when I want to display the post on the front page, it should only show the first 200 letters as well as keeping all breaks the user made in the textarea. What I am doing is the following:

substr($row["content"], 0, 200);

and this displays the content just fine, but it lets out all breaks that the user makes.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Daniel Alsaker
  • 193
  • 3
  • 15

3 Answers3

2

Apply newline to break function to your substring:

nl2br(substr($row["content"], 0, 200));

Or if you want to save whole words:

nl2br(mb_substr($row["content],0,200)); //this will not strip the word in the middle, so if it longer than 200 with the last word, it ends up before that word
pedrouan
  • 12,762
  • 3
  • 58
  • 74
  • This is just what I was looking for! Was exactly thinking about if there was a way to combine nl2br with substr as I've used them seperated from each other, was just not sure of how to combine them. Thank you C: – Daniel Alsaker Sep 05 '16 at 07:58
0

take a look here

How to get correctly content and avoid breaking html tags using strip_tags with substr?

Community
  • 1
  • 1
Reuben Gomes
  • 878
  • 9
  • 16
0

PHP's End Of Line

The correct 'End Of Line' symbol for PHP is the PHP_EOL constant. You can use PHP_EOL constant to replace the newline character in a cross-platform-compatible way with the br tag.

$row["content"] = str_replace(PHP_EOL,'<br>',$row["content"]);

Take a look at strip_tags

Strip_tags will remove all HTML,XML and PHP tags from a string. You can use the optional second parameter as a whitelist.

Keeping the BR tag

Use strip_tags with whitelisting br and substr in one line:

substr(strip_tags($row["content"],'<br>'), 0, 200);

Final code

Let's combine the replace and filter steps in one code block.

substr(strip_tags(str_replace(PHP_EOL,'<br>',$row["content"]),'<br>'), 0, 200);
Community
  • 1
  • 1
Neil Yoga Crypto
  • 615
  • 5
  • 16