Cut text and add ellipsis

Asked

Viewed 1,488 times

2

I need a function that cuts a text without cutting words, adding a "..." at the end.

3 answers

6

Here is a possibility in PHP, based in another answer:

$tamanho = 300;
$pos = strrpos( $texto.' ', ' ', $tamanho );
$retorno = substr( $texto, 0, $pos - 1 );
if ( $pos < strlen( $texto ) ) $retorno .= '...';

If you are going to use UTF-8 text, give preferences to the functions multibyte mb_strlen and mb_strrpos

  • One problem with this is that if the original text is less than the value specified in the third argument of the function strpos(), will return error strpos(): Offset not contained in string. Hence, it is safer a conditional to check the original size and compare with the character size for the "cut".

  • 1

    @Danielomine I don’t think you noticed $texto.' '. There will always be a space to be found;

  • got it! good technique, but still unnecessary because it invokes two functions to perform something that may not even be necessary in cases where the size of the original is less or equal to the cut.

  • If I don’t do the concatenation, which is "cheap" even in this context, I would have to add a greater complexity with if, Besides messing up the clarity of the code, so in the end I think it pays off. Anyway, remarks are always welcome to clarify the details.

5


You can do it this way:

<?php

function text_limiter_caracter($str, $limit, $suffix = '...')
{

    while (substr($str, $limit, 1) != ' ') {
        $limit--;
    }

    if (strlen($str) <= $limit) {
        return $str;
    }

    return substr($str, 0, $limit + 1) . $suffix;

}

$str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

echo text_limiter_caracter($str, 30, '...') . '<br>';
echo text_limiter_caracter($str, 60, '...') . '<br>';
echo text_limiter_caracter($str, 40, '...') . '<br>';
echo text_limiter_caracter($str, 80, '...') . '<br>';

Upshot:

Lorem ipsum dolor sit amet, ...
Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...
Lorem ipsum dolor sit amet, consectetur ...
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor ...

Another solution:

function text_limiter_caracter($str, $limit, $suffix = '...')
{

    if (strlen($str) <= $limit) return $str;
    $limit = strpos($str, ' ', $limit);
    return substr($str, 0, $limit + 1) . $suffix;

}

$str = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
$str2 = "Lorem ipsum dolor sit amet";

echo text_limiter_caracter($str, 60) . '<br>';
echo text_limiter_caracter($str, 40) . '<br>';
echo text_limiter_caracter($str, 80) . '<br>';
echo text_limiter_caracter($str2, 100) . '<br>';

Upshot:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed ...
Lorem ipsum dolor sit amet, consectetur adipisicing ...
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ...
Lorem ipsum dolor sit amet

1

An alternative containing conditionals to avoid error in the third function parameter mb_strpos().

So you don’t have to worry about the amount of characters in the original string

/**
O limite de caracteres.
*/
$limit = 10;

/**
A string original
*/
$str = 'lorem ipsum lorem1 ipsum1';

/**
Obtém a quantidade de caracters da string original
*/
$str_l = mb_strlen($str);

/**
Verifica se o limite é menor que a quantidade de caracters.
Caso o limite seja maior, a função mb_strpos() retornará erro de OffSet, por isso, essa verificação é necessária.
*/
echo (($limit < $str_l)? substr($str, 0, mb_strpos($str, ' ', $limit)).'...' : $str);

The problem with this technique or any other space character is that it is not valid in languages that do not have the space character. Therefore, it is not an internationalized solution.

I posted this answer in another question as well, because I believe the question here can be considered duplicate:

How to display part of a text stored in a TEXT column?

Solution with CSS

A solution that does not require PHP uses CSS features:

<style type="text/css">
.foo{
    border:1px solid #000;
    overflow:hidden;
    max-width:150px;
    max-height:20px;
    white-space:nowrap;
    text-overflow:ellipsis;
</style>

<div class="foo">dsfd fds dgdfg fdg fdgfdg fdg fd1132 errfgdfgf dgf6576576</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.