Добавить ... если строка слишком длинная PHP

у меня есть поле описания в моей базе данных MySQL, и я обращаюсь к базе данных на двух разных страницах, на одной странице я отображаю все поле, но на другой я просто хочу отобразить первые 50 символов. Если строка в поле описания меньше 50 символов, то она не будет отображаться ... но если нет, я покажу ... после первых 50 символов.

пример (полная строка):

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

Exmaple 2 (первые 50 символов):

Hello, this is the first example, where I am going ...

10 ответов


PHP способ сделать это просто:

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

но вы можете достичь гораздо более приятного эффекта с помощью этого CSS:

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

Теперь, предполагая, что элемент имеет фиксированную ширину, браузер автоматически отключится и добавит ... для вас.


вы также можете достичь желаемой отделки таким образом:

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

где:

  • Hello World: строка для обрезки.
  • 0: количество символов от начала строки.
  • 10: длина обрезанной строки.
  • ...: добавлена строка в конце обрезанной строки.

возвращает Hello W....

обратите внимание, что 10-это длина усе строка + добавленная строка!

документация:http://php.net/manual/en/function.mb-strimwidth.php


использовать wordwrap() для усечения строки не нарушая слова если строка длиннее 50 символов, и просто добавить ... в конце:

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

echo $str;

в противном случае, используя решения, что делать substr( $input, 0, 50); нарушит слова.


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

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

Я использую приведенный выше фрагмент кода много раз..


Я использую это решение на моем сайте. Если $str короче, чем $max, он останется неизменным. Если $str не имеет пробелов среди первых символов $max, он будет грубо сокращен в позиции $max. В противном случае 3 точки будут добавлены после последнего слова.

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

<?php
$string = 'This is your string';

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

вот и все.


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

это вернет заданную строку с многоточием на основе количества слов вместо символов:

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

можно использовать str_split() для этого

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