154

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

示例 2(前 50 个字符):

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

12 回答 12

382

这样做的 PHP 方法很简单:

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

但是你可以使用这个 CSS 实现更好的效果:

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

现在,假设元素具有固定宽度,浏览器将自动中断并...为您添加。

于 2012-07-11T13:50:04.527 回答
220

您也可以通过这种方式实现所需的修剪:

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

在哪里:

  • Hello World: 要修剪的字符串。
  • 0: 字符串开头的字符数。
  • 10:修剪后的字符串的长度。
  • ...:在修剪后的字符串末尾添加的字符串。

这将返回Hello W...

请注意,10 是截断字符串的长度 + 添加的字符串!

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

为避免截断单词:

在呈现文本摘录的情况下,可能应该避免截断一个单词。如果对截断文本的长度没有硬性要求,除了wordwrap()这里提到的之外,还可以使用以下方法来截断和防止截断最后一个单词。

$text = "Knowledge is a natural right of every human being of which no one
has the right to deprive him or her under any pretext, except in a case where a
person does something which deprives him or her of that right. It is mere
stupidity to leave its benefits to certain individuals and teams who monopolize
these while the masses provide the facilities and pay the expenses for the
establishment of public sports.";

// we don't want new lines in our preview
$text_only_spaces = preg_replace('/\s+/', ' ', $text);

// truncates the text
$text_truncated = mb_substr($text_only_spaces, 0, mb_strpos($text_only_spaces, " ", 50));

// prevents last word truncation
$preview = trim(mb_substr($text_truncated, 0, mb_strrpos($text_truncated, " ")));

在这种情况下,$preview"Knowledge is a natural right of every human being".

实时代码示例: http ://sandbox.onlinephpfunctions.com/code/25484a8b687d1f5ad93f62082b6379662a6b4713

于 2013-04-26T15:08:34.517 回答
50

如果字符串长度超过 50 个字符,则用于截断字符串而不破坏单词,并在wordwrap()末尾添加...

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

echo $str;

否则,使用确实的解决方案substr( $input, 0, 50);会破坏语言。

于 2012-07-11T13:50:56.803 回答
16
if (strlen($string) <=50) {
  echo $string;
} else {
  echo substr($string, 0, 50) . '...';
}
于 2012-07-11T13:50:05.637 回答
9
<?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;
}
?>

我多次使用上面的代码片段..

于 2012-07-11T13:50:26.170 回答
4

我在我的网站上使用此解决方案。如果 $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;
}
于 2017-01-25T11:53:59.983 回答
3

这将根据字数而不是字符返回带有省略号的给定字符串:

<?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);
?>
于 2017-09-25T18:49:00.767 回答
2
<?php
$string = 'This is your string';

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

就是这样。

于 2012-07-11T13:50:41.577 回答
2
$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
}
于 2012-07-11T13:51:35.483 回答
2
// this method will return the break string without breaking word
$string = "A brown fox jump over the lazy dog";
$len_required= 10;
// user strip_tags($string) if string contain html character
if(strlen($string) > 10)
{
 $break_str = explode( "\n", wordwrap( $string , $len_required));
 $new_str =$break_str[0] . '...';
}
// other method is use substr 
于 2019-09-13T07:01:20.400 回答
1

你可以用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;
于 2012-07-11T13:53:16.757 回答
0

对于一些使用 Yii2 的人来说,有一种方法yii\helpers\StringHelper::truncate()

使用示例:

$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."

这是文档:https ://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail

于 2020-02-20T12:26:08.173 回答