Sign in
Log inSign up

How does YouTube truncate their comments?

Lila Fowler's photo
Lila Fowler
·Mar 11, 2019

Hi everyone :)

I'm just wondering how YouTube does it. If a comment has over x lines or over x characters, it's truncated and the read more button shows the full comment.

I've tried duplicating the process, but I'm stuck somewhere between trying to truncate the comment if it exceeds x newlines AND/OR if it exceeds x characters. These are some ideas on how to do both of them:

stackoverflow.com/questions/8503028/cut-of…

stackoverflow.com/questions/6204759/how-to…

stackoverflow.com/questions/783899/how-can…

And I've done my own tinkering, like so:

$comment_content = $row['l_c_comment'];
//Because the comment has been sanitized in the DB, newlines show up as '\r\n' in phpmyadmin. This line of code replaces those with an html br tag or a space bar, which could've been a lot more sophisticated:
$full_comment = str_replace(['\r\n','\r','\n', '<br>'], ' ', $row['l_c_comment']);
$read_more = "....";
$read_more .= " <button class='read-more' data-fullcomment='".$full_comment."'>Read more</button>";
$allowedlimit = 500;
$allowedNewlines = 7;
$comment_content = strlen($comment_content) > $allowedlimit ? substr($comment_content, 0, $allowedlimit).$read_more : $comment_content;

...etc but that looks really messy as it is. How could I achieve truncating a comment if it exceeds 7 newlines or 500 characters, and then clicking a read-more button shows the full comment (in the same format of newlines/whitespaces), please ?

P.S. As a quick fix, I've just put a maximum height on the comments so that a scroll bar appears for comments over 13em. The character limit works fine as you can see here:

2019-03-11.png