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

Asked

Viewed 4,519 times

3

My table has a field TEXT where I insert text with paragraphs that are read through the function nl2br 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 I would like to know how to display only part of such a text or a paragraph only?

I’m not getting / knowing how to apply this exception. It would be in the $row2, echo, or neither? Could you help me?

  • vc want to display for example the 200 first characters of the text or is it display only a random paragraph? Each paragraph is separated one by one <br> . If possible put a short example text.

  • read the link: http://www.php.net/manual/en/function.explode.php and do so as I believe you will: $itens = explode("<br />", nl2br($row2['historia'])); echo $itens[0];

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 texts in UTF-8, give preferences to the functions multibyte 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']);

2

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);
?>

0

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.

Browser other questions tagged

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