php在字符断字处截断文字的代码

发布时间:2020-03-04编辑:脚本学堂
这里说的断字 (word break),即一个单词可在转行时断开的地方。下面这个函数将在断字处截断字符串。
复制代码 代码如下:

<?php
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=".", $pad="...") {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string, 100, ' ');
?>