Add ... if string is too long PHP

mais-oui picture mais-oui · Jul 11, 2012 · Viewed 149.3k times · Source

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 ...

Answer

Niet the Dark Absol picture Niet the Dark Absol · Jul 11, 2012

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.