截断字符串的选项

技术#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='&hellip;') {
       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;
}

?>

翻译自: https://css-tricks.com/snippets/php/truncate-strings/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值