Use substr directly on a foreach

Asked

Viewed 167 times

2

My scenario is this::

foreach ($exibe as $u) {
                echo "<div class='col-md-3'><div class='thumbnail'> ";
                echo "<img src='{$u->imagem}' height='120px' class='img-thumbnail'>";
                echo "<div class='caption'><h6>{$u->titulo}</h6>";
                echo "</div></div></div>";

I’m trying to display only the initial characters:

echo substr ({$u->titulo},0,50);

But to no avail.

  • 1

    Forehead echo "<div class='caption'><h6>".substr($u->titulo, 0, 50)."</h6>";

2 answers

5

Any problem doing this?

foreach ($exibe as $u) {
    $titulo = substr($u->titulo, 0, 50);
    echo "<div class='col-md-3'><div class='thumbnail'> ";
    echo "<img src='{$u->imagem}' height='120px' class='img-thumbnail'>";
    echo "<div class='caption'><h6>{$titulo}</h6>";
    echo "</div></div></div>";
}

Another way:

foreach ($exibe as $u) {
    echo "<div class='col-md-3'><div class='thumbnail'> ";
    echo "<img src='{$u->imagem}' height='120px' class='img-thumbnail'>";
    echo "<div class='caption'><h6>".substr($u->titulo, 0, 50)."</h6>";
    echo "</div></div></div>";
}

I put in the Github for future reference.

  • Vlw by help bigown most ended up choosing to use jquery: <script type="text/javascript"> $(Function(){ $(".limit").each(Function(i){ Len=$(this).text().length; if(Len>90) { $(this).text($(this).text().substr(0,100)+'...'); }); }); }); </script>

4


My solution would be to make use of the function wordwrap() to collect X characters, passing the result to the function explode() to break the output in lines and finally stay only with the first line which is effectively the intended:

$titulo = explode("\n", wordwrap($u->titulo, 50))[0];

Example:

$titulo = "Isto é um título de alguma coisa que carece ter um título, mas como é muito grande, vou cortar e meter uns pontinhos no final";

$manter = 50;

$titulo = explode("\n", wordwrap($titulo, $manter))[0];

var_dump($titulo);  // Saída: string(49) "Isto é um título de alguma coisa que carece ter"

See example in Ideone.

This way, we are breaking the string but avoid breaking words in half.

In your case:

For your particular case I would be:

foreach ($exibe as $u) {

  $titulo = explode("\n", wordwrap($u->titulo, 50))[0].'...';

  echo '
  <div class="col-md-3">
    <div class="thumbnail">
      <img src="'.$u->imagem.'" height="120px" class="img-thumbnail">
      <div class="caption">
        <h6>'.$titulo.'</h6>
      </div>
    </div>
  </div>';
}

Example of the final result in Jsfiddle.

Captura de tela de simulação do resultado


Considerations

When we cut a string to later add ..., we have to be aware of two things:

  1. Don’t break the words in half so you don’t miss reading:

    We’ve seen how to handle this.

  2. Not add ... if there was no actual cut:

    For this case, we can optimize the code by passing the work of the cut to a function, which function that when returning the result will check first if there was an actual cut in the string provided:

    /**
     * Cortar String
     * Vai cortar a string recebida e adicionar "..." apenas se a mesma
     * tiver mais caracteres do que os indicados para manter.
     *
     * @param string $str String a cortar
     * @param integer $keep Número de caracteres a manter (por defeito 50)
     *
     * @return string Texto pronto a usar
     */
    function cortarStr ($str, $keep=50) {
    
      if (strlen($str)>$keep)
        $str = explode("\n", wordwrap($str, 50))[0] . '...';
    
      return $str;
    } 
    

    See example in Ideone.

Browser other questions tagged

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