我命名功能str_trunc
。你可以指定strict爲TRUE,在這種情況下,它只允許一個最大大小的字符串,不會再有更多的字符串,否則它會搜索它即將完成的單詞中最短的字符串。
var_dump(str_trunc('How are you today?', 10)); // string(10) "How are..."
var_dump(str_trunc('How are you today? ', 10, FALSE)); // string(14) "How are you..."
// Returns a trunctated version of $str up to $max chars, excluding $trunc.
// $strict = FALSE will allow longer strings to fit the last word.
function str_trunc($str, $max, $strict = TRUE, $trunc = '...') {
if (strlen($str) <= $max) {
return $str;
} else {
if ($strict) {
return substr($str, 0, strrposlimit($str, ' ', 0, $max + 1)) . $trunc;
} else {
return substr($str, 0, strpos($str, ' ', $max)) . $trunc;
}
}
}
// Works like strrpos, but allows a limit
function strrposlimit($haystack, $needle, $offset = 0, $limit = NULL) {
if ($limit === NULL) {
return strrpos($haystack, $needle, $offset);
} else {
$search = substr($haystack, $offset, $limit);
return strrpos($search, $needle, 0);
}
}
可能重複[如何截斷PHP中的字符串?](http://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-in-php) – Stephen
因此'trim_me ('a bbbbbbbbbbbbbbbbbbbbbbbb c',10)''會是''a bbbbbbbbbbbbbbbbbbbbbbbb ...''? – ruakh
我得到'string(10)「如何...」'trim_me($ s,10) –