How to limit PHP words

Asked

Viewed 2,045 times

5

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, I’d be like,:

Lorem ipsum Dol...

<?php $row['title']; ?>

4 answers

3


You can do this in a simple way:

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

Methodically:

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

2

Simple imprementation by fixed number of characters:

$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;

0

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

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

0

Solution in PHP

Use the 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 I’d 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

Browser other questions tagged

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