Limit characters received from a database field

I start when it comes to PHP.

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

echo $fieldname;

One of these fields is information about something I want to do is limit the number of characters received so that only 150 characters are displayed.

Does anyone know how to do this?

+5
source share
3 answers

You can do this 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 probably want to cut it after the word. You can use the following function for this (it will cut str when it is long, and place it behind it ...):

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

    return $str;
}

. , , - , , , CSS3 text-overflow: jsFiddle

+3

substr PHP

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

echo substr($fieldname, 0, 150);

, , . MySQL, MS SQL LEFT(..), .

.

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

If you care about the cut so that you do not 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.

0
source

All Articles