我的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 ...
答案 0 :(得分:272)
PHP的做法很简单:
$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;
但是你可以用这个CSS实现更好的效果:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
现在,假设元素具有固定宽度,浏览器将自动中断并为您添加...
。
答案 1 :(得分:150)
您也可以通过这种方式实现所需的修剪:
mb_strimwidth("Hello World", 0, 10, "...");
其中:
Hello World
:要剪裁的字符串。0
:字符串开头的字符数。10
:修剪过的字符串的长度。...
:修剪过的字符串末尾添加的字符串。这将返回Hello W...
。
请注意,10是截断字符串的长度+添加的字符串!
答案 2 :(得分:36)
如果字符串超过50个字符,请使用wordwrap()
截断字符串而不会破坏字词,并在结尾处添加...
:
$str = $input;
if( strlen( $input) > 50) {
$str = explode( "\n", wordwrap( $input, 50));
$str = $str[0] . '...';
}
echo $str;
否则,使用substr( $input, 0, 50);
的解决方案会破坏单词。
答案 3 :(得分:12)
if (strlen($string) <=50) {
echo $string;
} else {
echo substr($string, 0, 50) . '...';
}
答案 4 :(得分:5)
<?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;
}
?>
我多次使用上面的代码片段。
答案 5 :(得分:2)
我在我的网站上使用此解决方案。如果$ str比$ max更短,它将保持不变。如果$ str在前$ $字符中没有空格,则会在$ 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;
}
答案 6 :(得分:2)
这将返回一个给定的字符串,其中包含基于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);
?>
答案 7 :(得分:1)
<?php
$string = 'This is your string';
if( strlen( $string ) > 50 ) {
$string = substr( $string, 0, 50 ) . '...';
}
就是这样。
答案 8 :(得分:1)
$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
}
答案 9 :(得分:0)
您可以将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;
答案 10 :(得分:0)
Alter PROCEDURE DateToInterval
-- Add the parameters for the stored procedure here
@start datetime,
@end datetime,
@interval int
AS
BEGIN
declare @start_run as datetime
declare @end_run as datetime
declare @counter as int
--temp table to store interval
create table #tempinterval(
StartDate datetime,
EndDate datetime,
IntervalCounter varchar(20)
)
--update start, end date if it is weekend
set @start_run=DBTest.dbo.Check_Weekend_And_Update_With_WeekDays(@start,'add')
set @end_run=DBTest.dbo.Check_Weekend_And_Update_With_WeekDays(@start,'remove')
set @end=DBTest.dbo.Check_Weekend_And_Update_With_WeekDays(@end,'remove')
set @counter=1
--select @start_run as 'start', @end as 'end'
While(@end_run <= @end)
Begin
--select 'loop'
--adding interval on start date
set @end_run = DATEADD(DAY, @interval-1, cast(@start_run as datetime))
if(@end_run > @end)
BEGIN
set @end_run=@end
END
--to check if it is weekend and replace it week next weekdays
set @end_run=DBTest.dbo.Check_Weekend_And_Update_With_WeekDays(@end_run,'add')
insert into #tempinterval(StartDate,EndDate,IntervalCounter) values(@start_run,@end_run,'Interval '+ cast(@counter as varchar))
set @end_run=DATEADD(DAY, 1, cast(@end_run as datetime))
--update end date if it is weekend
set @end_run=DBTest.dbo.Check_Weekend_And_Update_With_WeekDays(@end_run,'add')
set @start_run=@end_run
set @counter =@counter + 1
END
select * from #tempinterval
END
GO
答案 11 :(得分: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