How to limit PHP words

4

Hello, I would like to know how I limit the text I pull from the database.

For example, I have a text called:

Lorem ipsum dolor sit amet.

And I wanted you to limit the text by pulling, it would look like:

Lorem ipsum dol ...

<?php $row['title']; ?>
    
asked by anonymous 26.06.2015 / 18:41

4 answers

1

You can do this in a simple way:

echo substr($row['title'],0,26).'...'; ?>

With method:

function limitChars($text, $limit=20)
{
  return substr($text, $limit).'...';
}
echo limitChars($row['title'], 26);

Or, with method without breaking words; consider that every string in PHP is an array, just break it in the spaces:


function limitChars($text, $limit=4)
{
 $join = array();
 $ArrayString = explode(" ", $text);

    if ($limit > count($ArrayString)) {
        $limit = count($ArrayString) / 2;   
    }

    foreach ($ArrayString as $key => $word) {
              $join[] = $word;
           if ($key == $limit) {
               break;
         }
    }
    //print_r($join);
    return implode(" ", $join)."...";

}
echo limitChars($row['title'], 3);
    
29.06.2015 / 22:37
2

Simple Static Number Impregnation:

$texto= strip_tags($texto);

if (strlen($texto) > 500) {

    // Limitando string
    $corteTexto= substr($texto, 0, 500);

    //certifique-se que termina em uma palavra...
    $texto= substr($corteTexto, 0, strrpos($corteTexto, ' ')).'...'; 
}
echo $texto;
    
26.06.2015 / 20:36
0

You can use the substr() function and do something like this:

<?php
    $variavel = substr($row['title'], 0, -5))
?>

<spam title="<= $row['title']; ?>"><= $variavel ?>...</span>

substr("texto a ser limitado", onde inicia, onde termina)

Exps:

substr("texto a ser limitado", 0, -5)
Saida: texto a ser lim
substr("texto a ser limitado", 5, -2)
Saida:  a ser limita
    
26.06.2015 / 18:52
0

Solution in PHP

Use substr

Example, limiting up to 15 letters:

$title = "Lorem ipsum dolor sit amet.";
echo substr($title, 0, 15) . '...';
  

Lorem ipsum dol ...

IdeOne Example

In your case you would do something like this:

<?php echo substr($row['title'], 0, 15) . '...'; ?>


Solution in MySQL

SELECT CONCAT(SUBSTRING(valor, 1, 15), '...') as valor
FROM teste

SqlFiddle Example

    
26.06.2015 / 18:54