简体   繁体   中英

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?

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

You can use substr in PHP

$fieldname = substr($fieldname, 0, 150); 

or just

echo substr($fieldname, 0, 150);

Alternatively, limit the number of characters that your database query returns, eg MySQL and MS SQL both have a LEFT(..) function which will restrict the data returned.

ie

SELECT LEFT(FieldName, 150) AS FieldName FROM MyTable WHERE ...

If you care about the cut so that you don't want to cut the sentence inside the word you can use this function:

function safeShrinkText($text, $length = 100, $suffix = '...')
{
    $text = strip_tags($text);
    if ($length > strlen($text)) {
        return $text;
    }

    while (!isset($text[$length]) || $text[$length] != ' ' && $length != 0) {
        $length--;
    }

    return mb_substr($text, 0, $length) . $suffix;
}

This function will not cut the sentence inside the word.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM