Character limit

2

I need to limit characters in a text, and should stick with (...). The title goes out of the layout.

if($related){
    echo '
    <div class="row">
        <div class="medium-12 columns">
            <div class="ap-ads-related">
                <h2>Anúncios Relacionados</h2>
                <div class="row">
    ';

    foreach ($related as $key => $rel) {
        $related_images = $this->ads_model->images($rel->ad_id);
        $related_image = thumbnail(@$related_images[0]->ads_img_file, "ads", 260, 180, 2);

        echo '
            <div class="small-6 medium-3 end columns">
                <a href="'.base_url('anuncio/'.$rel->ad_slug).'" title="'.$rel->ad_name.'" class="item">
                    <div class="image"><img alt="'.$rel->ad_name.'" src="'.$related_image.'"></div>

                    <h4>'.$rel->ad_name.'</h4>

                    <div class="price">'.(($rel->ad_service) ? 'Serviço' : string_money($rel->ad_price)).'</div>
                </a>
            </div>
        ';
    }
    echo '
                </div>
            </div>  
        </div>
    </div>
    ';
}

?>
    
asked by anonymous 01.11.2016 / 09:48

4 answers

7

Codeigniter itself has a function for this, I believe it should be using it because it stuck the same in the question. You can limit by characters or by words, following code:

<?php print character_limiter($rel->ad_name, 25); ?>

It will limit by 25 characters and after that it will insert ...

<?php print word_limiter($rel->ad_name, 25); ?>

You will limit it by 25 words and after it will appear ...

If you have questions, follow the Codeigniter link with some information: link

    
01.11.2016 / 11:42
1

I created a helper named my_strings.php in the Application/Helpers folder

<?php

  function cortaTexto($string, $maxLength){
     if(strlen($string) <= $maxLength)
        return $string;

     return substr($string, 0, $maxLength) . '...';
  }

?>

Add this helper in autoload.php ,

$autoload['helper'] = array('html', 'url', 'my_strings');

Then in View:

cortaTexto($rel->ad_name, 30)
    
01.11.2016 / 11:36
1

Man, you can also solve this with css.

This is the links that helped me when I needed it,

link

link

link

UPDATE

Set the width of the container and put text-overflow: ellipsis and when it arrives at the border of the container the text will be automatically replaced with ...

See example of css-tricks

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
    
01.11.2016 / 11:58
0

Very simple example:

$string = 'String para ser reduzida'
$reduzido = substr_replace($string, (strlen($string) > 42 ? '...' : ''),42);

I hope it helps.

    
01.11.2016 / 13:13