web-dev-qa-db-fra.com

Ajouter ... si la chaîne est trop longue PHP

J'ai un champ de description dans ma base de données MySQL et j'accède à la base de données sur deux pages différentes. L'une affiche le champ entier, mais de l'autre, je souhaite uniquement afficher les 50 premiers caractères. Si la chaîne dans le champ de description contient moins de 50 caractères, elle ne s'affichera pas ..., mais si ce n'est pas le cas, je montrerai ... après les 50 premiers caractères.

Exemple (chaîne complète):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

Exemple 2 (50 premiers caractères):

Hello, this is the first example, where I am going ...
102
mais-oui

La manière de faire PHP) est simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

Mais vous pouvez obtenir un effet beaucoup plus agréable avec ce CSS:

.Ellipsis {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: Ellipsis;
}

Maintenant, en supposant que l'élément ait une largeur fixe, le navigateur s'interrompt automatiquement et ajoute le ... pour vous.

284
Niet the Dark Absol

Vous pouvez également obtenir la finition souhaitée de la manière suivante:

mb_strimwidth("Hello World", 0, 10, "...");

Où:

  • Hello World: la chaîne à couper.
  • 0: nombre de caractères depuis le début de la chaîne.
  • 10: la longueur de la chaîne coupée.
  • ...: une chaîne ajoutée à la fin de la chaîne coupée.

Cela retournera Hello W....

Notez que 10 est la longueur de la chaîne tronquée + la chaîne ajoutée!

Documentation: http://php.net/manual/en/function.mb-strimwidth.php

162
jim_kastrin

Utilisez wordwrap() pour tronquer la chaîne sans séparer les mots si la chaîne contient plus de 50 caractères, et ajoutez simplement ... À la fin:

$str = $input;
if( strlen( $input) > 50) {
    $str = explode( "\n", wordwrap( $input, 50));
    $str = $str[0] . '...';
}

echo $str;

Sinon, utiliser des solutions qui font substr( $input, 0, 50); cassera les mots.

36
nickb
if (strlen($string) <=50) {
  echo $string;
} else {
  echo substr($string, 0, 50) . '...';
}
12
Tchoupi
<?php
function truncate($string, $length, $stopanywhere=false) {
    //truncates a string to a certain char length, stopping on a Word if not specified otherwise.
    if (strlen($string) > $length) {
        //limit hit!
        $string = substr($string,0,($length -3));
        if ($stopanywhere) {
            //stop anywhere
            $string .= '...';
        } else{
            //stop on a Word.
            $string = substr($string,0,strrpos($string,' ')).'...';
        }
    }
    return $string;
}
?>

J'utilise l'extrait de code ci-dessus plusieurs fois.

5
verisimilitude

J'utilise cette solution sur mon site web. Si $ str est plus court que $ max, il restera inchangé. Si $ str n'a pas d'espace entre les premiers caractères $ max, il sera brutalement coupé à la position $ max. Sinon, 3 points seront ajoutés après le dernier mot entier.

function short_str($str, $max = 50) {
    $str = trim($str);
    if (strlen($str) > $max) {
        $s_pos = strpos($str, ' ');
        $cut = $s_pos === false || $s_pos > $max;
        $str = wordwrap($str, $max, ';;', $cut);
        $str = explode(';;', $str);
        $str = $str[0] . '...';
    }
    return $str;
}
2
Webars

Cela retournera une chaîne donnée avec Ellipsis basée sur le nombre de mots au lieu de caractères:

<?php
/**
*    Return an elipsis given a string and a number of words
*/
function elipsis ($text, $words = 30) {
    // Check if string has more than X words
    if (str_Word_count($text) > $words) {

        // Extract first X words from string
        preg_match("/(?:[^\s,\.;\?\!]+(?:[\s,\.;\?\!]+|$)){0,$words}/", $text, $matches);
        $text = trim($matches[0]);

        // Let's check if it ends in a comma or a dot.
        if (substr($text, -1) == ',') {
            // If it's a comma, let's remove it and add a Ellipsis
            $text = rtrim($text, ',');
            $text .= '...';
        } else if (substr($text, -1) == '.') {
            // If it's a dot, let's remove it and add a Ellipsis (optional)
            $text = rtrim($text, '.');
            $text .= '...';
        } else {
            // Doesn't end in dot or comma, just adding Ellipsis here
            $text .= '...';
        }
    }
    // Returns "ellipsed" text, or just the string, if it's less than X words wide.
    return $text;
}

$description = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!';

echo elipsis($description, 30);
?>
2
Lucas Bustamante
<?php
$string = 'This is your string';

if( strlen( $string ) > 50 ) {
   $string = substr( $string, 0, 50 ) . '...';
}

C'est ça.

1
Berry Langerak
$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";

if(strlen($string) >= 50)
{
    echo substr($string, 50); //prints everything after 50th character
    echo substr($string, 0, 50); //prints everything before 50th character
}
1
Nikola K.

Vous pouvez utiliser str_split() pour cela

$str = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don't know how long maybe around 1000 characters. Anyway this should be over 50 characters know...";
$split = str_split($str, 50);
$final = $split[0] . "...";
echo $final;
0
alfrodo