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

在我的 MySQL 数据库中有一个描述字段,我在两个不同的页面上访问数据库,一个页面显示整个字段,但是在另一个页面上,我只想显示前50个字符。如果 description 字段中的字符串小于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 ...
198412 次浏览

PHP 的方法很简单:

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

但是你可以通过这个 CSS 获得更好的效果:

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

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

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

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

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


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

就是这样。

如果字符串长于50个字符,则使用 wordwrap()截断字符串 不用说话,并在结尾处添加 ...:

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


echo $str;

否则,使用 substr( $input, 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
}

您可以使用 强 > 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;

你也可以通过这种方式达到理想的修剪效果:

mb_strimwidth("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

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

这将根据 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);
?>
// 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

对于一些使用 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