我有这个功能:
function shorter($text, $chars_limit) {
if (strlen($text) > $chars_limit)
return substr($text, 0, strrpos(substr($text, 0, $chars_limit), " ")).'...';
else return $text;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用echo shorter($input, 11)
它工作正常,但如果输入中有一些空格,否则输入看起来像:
wwwwwwwwwww
该功能将此更改为:
......(3点).
我不想改成这样的东西:
www ...
您有任何想法如何重建此脚本?先感谢您.
Ada*_*dam 11
我假设你只是想接受一个输入.如果它长于X,则在X处将其切断并添加"...".
// Start function
function shorter($text, $chars_limit)
{
// Check if length is larger than the character limit
if (strlen($text) > $chars_limit)
{
// If so, cut the string at the character limit
$new_text = substr($text, 0, $chars_limit);
// Trim off white space
$new_text = trim($new_text);
// Add at end of text ...
return $new_text . "...";
}
// If not just return the text as is
else
{
return $text;
}
}
Run Code Online (Sandbox Code Playgroud)
我没有测试这个,但它应该工作.:)
如果您正在寻找修剪一些实际文本的函数,您可能需要一个 UTF-8 安全函数。此外,如果您想稍微智能地修剪文本(仅在字母数字字符之后修剪文本,而不是 HTML 等),您可以尝试我写的这个函数:
/**
* shortens the supplied text after last word
* @param string $string
* @param int $max_length
* @param string $end_substitute text to append, for example "..."
* @param boolean $html_linebreaks if LF entities should be converted to <br />
* @return string
*/
function mb_word_wrap($string, $max_length, $end_substitute = null, $html_linebreaks = true) {
if($html_linebreaks) $string = preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
$string = strip_tags($string); //gets rid of the HTML
if(empty($string) || mb_strlen($string) <= $max_length) {
if($html_linebreaks) $string = nl2br($string);
return $string;
}
if($end_substitute) $max_length -= mb_strlen($end_substitute, 'UTF-8');
$stack_count = 0;
while($max_length > 0){
$char = mb_substr($string, --$max_length, 1, 'UTF-8');
if(preg_match('#[^\p{L}\p{N}]#iu', $char)) $stack_count++; //only alnum characters
elseif($stack_count > 0) {
$max_length++;
break;
}
}
$string = mb_substr($string, 0, $max_length, 'UTF-8').$end_substitute;
if($html_linebreaks) $string = nl2br($string);
return $string;
}
Run Code Online (Sandbox Code Playgroud)