>我有以下函数来截断文本:
/**
* Removes HTML tags, crops to 255 symbols
*
* @param string $unformatted
*/
public function formatShortDescr($unformatted) {
if(strlen($unformatted)<1) return;
$long_text = strip_tags(trim($unformatted));
$max_length = 255;
if(strlen($long_text) > $max_length){
$short_text = (substr($long_text,0,$max_length));
} else {
$short_text = $long_text;
}
return $short_text;
}
例如: <p>Victory har utvecklats för att passa den ägare som behöver en kompakt, ........
转换为:Victory har utvecklats för att passa den &a
如何将其设置为在中断 html 实体的中途永远不会剪切字符串?
应该很容易先将
实体转换为普通字符,然后使用mb_strlen(因为 2 字节字符,UTF8)检查长度和截断mb_substring,然后将实体转换回来......
$long_text = strip_tags(trim($unformatted));
$long_text = html_entity_decode($long_text);
$long_text = mb_strlen($long_text) > $max_length ? mb_substr($long_text, 0, $max_length) : $long_text;
return htmlentities($long_text);
有时合适的另一种方法是在最后一个空格处截断。这取决于您是否想要正好 255 个字符,或者您是否想要可读的内容,但一个有用的副作用是您不必担心 HTML 实体。
例如:
$string = "this is the long test string to test with";
$limit = 20;
$result = substr($string, 0, strrpos($string, " ", -$limit)-1);
echo $result; // "this is the long"