添加 ... 如果字符串太长 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11434091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:30:58  来源:igfitidea点击:

Add ... if string is too long PHP

phpstringstrlen

提问by mais-oui

I have a description field in my MySQL database, and I access the database on two different pages, one page I display the whole field, but on the other, I just want to display the first 50 characters. If the string in the description field is less than 50 characters, then it won't show ... , but if it isn't, I will show ... after the first 50 characters.

我的 MySQL 数据库中有一个描述字段,我在两个不同的页面上访问数据库,一个页面显示整个字段,但在另一个页面上,我只想显示前 50 个字符。如果 description 字段中的字符串少于 50 个字符,那么它不会显示 ... ,但如果不是,我会在前 50 个字符之后显示 ... 。

Example (Full 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 now ...

Exmaple 2 (first 50 characters):

示例 2(前 50 个字符):

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

回答by Niet the Dark Absol

The PHP way of doing this is simple:

PHP 执行此操作的方法很简单:

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

But you can achieve a much nicer effect with this CSS:

但是您可以使用此 CSS 实现更好的效果:

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

Now, assuming the element has a fixed width, the browser will automatically break off and add the ...for you.

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

回答by jim_kastrin

You can achieve the desired trim in this way too:

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

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

Where:

在哪里:

  • Hello World: the string to trim.
  • 0: number of characters from the beginning of the string.
  • 10: the length of the trimmed string.
  • ...: an added string at the end of the trimmed string.
  • Hello World: 要修剪的字符串。
  • 0: 从字符串开头开始的字符数。
  • 10:修剪后的字符串的长度。
  • ...: 在修剪后的字符串末尾添加一个字符串。

This will return Hello W....

这将返回Hello W...

Notice that 10 is the length of the truncated string + the added string!

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

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

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

回答by nickb

Use wordwrap()to truncate the string without breaking wordsif the string is longer than 50 characters, and just add ...at the end:

使用wordwrap()截断字串不打破的话如果字符串超过50个字符,并且只需添加...在最后:

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

echo $str;

Otherwise, using solutions that do substr( $input, 0, 50);will break words.

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

回答by Tchoupi

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

回答by verisimilitude

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

I use the above code snippet many-a-times..

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

回答by Webars

I use this solution on my website. If $str is shorter, than $max, it will remain unchanged. If $str has no spaces among first $max characters, it will be brutally cut at $max position. Otherwise 3 dots will be added after the last whole word.

我在我的网站上使用此解决方案。如果 $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;
}

回答by Lucas Bustamante

This will return a given string with ellipsis based on WORD count instead of characters:

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

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

回答by Berry Langerak

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

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

That's it.

就是这样。

回答by Nikola K.

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

回答by alfrodo

You can use str_split()for this

你可以用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;