Use substr directly in a foreach

2

My scenario is as follows:

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 without success.

    
asked by anonymous 28.12.2014 / 22:18

2 answers

4

My solution would be to use the wordwrap() function to collect X characters, passing the result for the explode() function to break the output into rows and finally get only the first line that is effectively 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 on Ideone .

In this way, we are starting from the string but avoid breaking words in half.

For your case:

For your particular case it would look like:

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 the JSFiddle .

Considerations

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

  • Do not break words in half so as not to lose reading:

    We've already seen how to deal with this.

  • Do not add ... if there really was no cut:

    For this case, we can optimize the code by passing the cut job to a function, which returns the result, first checking to see if a cut in the given string actually existed:

    /**
     * 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 on Ideone .

  • 30.12.2014 / 14:01
    5

    Is there a problem in 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>";
    }
    
        
    28.12.2014 / 22:27