方法 #1:简单
function myTruncate($string, $limit, $break=".", $pad="...") {
if(strlen($string) <= $limit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad; }
} return $string;
}
方法 #2:简单
function ellipsis($text, $max=100, $append='…') {
if (strlen($text) <= $max) return $text;
$out = substr($text,0,$max);
if (strpos($text,' ') === FALSE) return $out.$append;
return preg_replace('/\w+$/','',$out).$append;
}
用法
<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>
方法 #3:更多选项
使用 PHP 的 php_tidy 修复损坏的 HTML,或完全去除 HTML 的选项。
function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
if ( strlen( $input ) >= $limit ) {
$breakpoint = strpos( $input, $break, $limit );
$input = substr( $input, 0, $breakpoint ) . $end_text;
}
if ( $tidy_html == 1 ) {
ob_start( );
$tidy = new tidy;
$config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
$tidy->parseString( $input, $config, 'utf8' );
$tidy->cleanRepair( );
$input = $tidy;
}
if ( $strip_html == 1 ) {
$input = strip_tags( $input );
}
return $input;
}
方法 #4:无需函数
<?php
$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$max_length = 40; // we want to show only 40 characters.
if (strlen($long_text) > $max_length)
{
$short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long
$short_text .= "..."; // add an ellipses ... at the end
$short_text .= "<a href='http://example.com/page.html'>Read more</a>"; // add a link
echo $short_text;
}
else
{
// string is already less than $max_length, so display the string as is
echo $long_text;
}
?>
我正在使用
<?php the_tags('','',''); ?>
来输出标签。但是,如果标签很长,我将其保存在主题中的位置可能会出现问题。如何将单个标签保持在一定数量的字母以内,并在末尾添加省略号?
看起来这是一个 WordPress 函数。您可能想要尝试使用 get_the_tags() 而不是 the_tags()。Get 版本将返回一个数组而不是输出结果。然后,您可以在输出之前截断数组中的字符串。
Ciao Simon,抱歉使用这种非传统的方式联系您。我只是想说,如果您在 HomeAway 上搜索 Belvedere Villa Mezzomonte 并通过那里联系我,您无需支付客人费用,这应该可以为您节省大约 10% 的费用。谢谢,Davide
谢谢,我会试试的。非常有帮助!
使用了第一个 :)
谢谢,非常有帮助
当我看到
if(false !==
谢谢,Chris。
我在一个插件中使用了方法 #2:简单,用于在侧边栏显示所有博主的简短描述。