Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting characters retrived from a database field

I am a novice when it comes to PHP.

I am using Wordpress with ACF (Advanced Custom Fields), so any data I get from a field I use the code below:

echo $fieldname;

One of these fields is for information about something, what I want to do is limit the amount of characters retrieved so that only 150 character are displayed.

Anyone have any idea how to do this?

like image 768
Will Thompson Avatar asked Oct 23 '22 09:10

Will Thompson


1 Answers

You can do it with substr:

$str = "Aliquam odio eros, consectetur eu euismod faucibus, venenatis lobortis nulla. Pellentesque libero massa, bibendum in tempus ut, pretium et ante. In bibendum volutpat porta. ";

echo substr($str, 0, 150);

But if you have a long string, then you probaly want to cut it after an word. You can use the following function for this (it will cut of the str when it's to long and place the ... behind it):

function truncate_string($str, $length) {
    if (!(strlen($str) <= $length)) {
        $str = substr($str, 0, strpos($str, ' ', $length)) . '...';
    }

    return $str;
}

Client side

You can also do it on the client side. I don't know what you try to achieve, but if it's an title or something and you don't want it to be too long and ruin your layout then you can use CSS3 text-overflow: jsFiddle example

like image 63
Sven van Zoelen Avatar answered Nov 02 '22 08:11

Sven van Zoelen