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

2

My table has a TEXT field where I enter text with paragraphs that are read through the nl2br function of PHP.

I print each column of the table through mysql_fetch_array and everything is displayed correctly:

$res2 = mysql_query("SELECT * FROM 'entrada' WHERE 'id_destino' =".$_GET['id']);
$row2 = mysql_fetch_array($res2);
echo nl2br($row2['historia']);

As I said earlier, my text has several paragraphs, but would you like to know how do I display only a portion of that text or a paragraph only?

I'm not getting / knowing how to apply this exception. Would it be in $row2 , echo , or in neither? can you help me?

    
asked by anonymous 16.04.2014 / 17:12

3 answers

5

Here are several examples to illustrate the possibilities. Just understand the basic logic, and recombine according to the desired result!

Solutions with PHP:

<?php
   $res2 = mysql_query("SELECT * FROM 'entrada' WHERE 'id_destino' =".$_GET['id']);
   $row2 = mysql_fetch_array($res2);

   $historia = $row2['historia'];

   // Mostrar os primeiros 300 caracteres:
   echo nl2br(
      substr($historia, 0, 300)
   );

   // Mostrar o primeiro parágrafo com PHP 5.3 ou maior:
   echo nl2br(
      strstr($historia, chr(10), true);
   );

   // Mostrar o primeiro parágrafo:
   echo nl2br(
      substr($historia, 0, strpos($historia, chr(10) ) - 1);
   );

   // Mostrar o primeiro parágrafo, ou o próximo,
   // se este tiver menos  de 100 caracteres:
   echo nl2br(
      substr($historia, 0, strpos($historia, chr(10), 100 ) - 1);
   );

   // Mostrar cerca de 300 caracteres, mas sem quebrar palavras:
   echo nl2br(
      substr($historia, 0, strpos($historia, ' ', 300 ) - 1);
   );

?>

Note: If you are going to use UTF-8 text, give multibyte functions mb_substr and mb_strpos

Solutions with SQL:

$id = 0 + $_GET['id']; // SEU SCRIPT ORIGINAL É PORTA PARA SQL INJECTION! 
                       // USE mysqli_ E BINDING NO LUGAR DE mysql_

//Primeiros 200 caracteres:
$query = "SELECT LEFT('historia',200) FROM 'entrada' WHERE 'id_destino' = $id"

//Primeiro paragrafo:
$query = "SELECT LEFT('historia',INSTR('historia',CHAR(10))-1) FROM 'entrada' WHERE 'id_destino' = $id"

//Cerca de 200 caracteres, quebrando entre palavras :
$query = "SELECT LEFT( 'historia', 199 + INSTR( SUBSTR( 'historia', 200 ),' ' ) ) FROM 'entrada' WHERE 'id_destino' = $id"

$res2 = mysql_query($query);
$row2 = mysql_fetch_array($res2);
echo nl2br($row2['historia']);
    
16.04.2014 / 20:14
1

You can use the substr () function as follows:

string substr ( string $string , int $start [, int $length ] )

Source: Substr Function (php.net)

It would look like this to show the first 30 characters:

echo substr(nl2br($row2['historia']), 0, 30);

or

<?php
function textLimit($string, $length, $replacer = '...'){
  if(strlen($string) > $length)
  return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
  return $string;
}

echo textLimit($row2['historia'], 30);
?>
    
16.04.2014 / 17:25
0

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

That way you do not 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 others that use the space character is not valid in languages that do not have the space character. So it's not an internationalized solution.

    
08.11.2015 / 21:25