Add ... if string is too long PHP [duplicate]

I have a description field in my MySQL database, and I access the database on two different pages, one page I display the whole field, but on the other, I just want to display the first 50 characters. If the string in the description field is less than 50 characters, then it won't show ... , but if it isn't, I will show ... after the first 50 characters.

Example (Full string):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

Exmaple 2 (first 50 characters):

Hello, this is the first example, where I am going ...

Solution 1:

The PHP way of doing this is simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

But you can achieve a much nicer effect with this CSS:

.ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

Now, assuming the element has a fixed width, the browser will automatically break off and add the ... for you.

Solution 2:

You can achieve the desired trim in this way too:

mb_strimwidth("Hello World", 0, 10, "...");

Where:

  • Hello World: the string to trim.
  • 0: number of characters from the beginning of the string.
  • 10: the length of the trimmed string.
  • ...: an added string at the end of the trimmed string.

This will return Hello W....

Notice that 10 is the length of the truncated string + the added string!

Documentation: http://php.net/manual/en/function.mb-strimwidth.php

To avoid truncating words:

In case of presenting text excerpts, probably truncating a word should be avoided. If there is no hard requirement on the length of the truncated text, apart from wordwrap() mentioned here, one can use the following to truncate and prevent cutting the last word as well.

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

In this case, $preview will be "Knowledge is a natural right of every human being".

Live code example: http://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713