Truncate/shorten 文本导致 HTML 实体编码错误

Truncate/shorten text causes encoding error on HTML Entities

我正在建立一个关于健康的网站。我需要在 table 中显示一些症状及其数据。但是,某些症状的名称太长,导致布局问题。所以,我找到了一种方法来缩短他们的名字 PHP,如下所示:

<?=strlen($a)>45 ? stripslashes(substr($a, 0, 45)."...") : stripslashes($a)?>

它工作正常。唯一的问题是当字符串在 HTML Entity, which causes the browser to display a diamond with a question mark instead (http://prntscr.com/dzqyps).

中间被切断时

示例:

原字符串:

超过 x 个字符的长字符串以 já 结尾

截断的字符串:

超过 x 个字符的长字符串结束 j&aa...

浏览器中显示的字符串:

超过 x 个字符的长字符串以 j 结尾?...

我该如何解决这个问题?

哈哈...我能在短时间内做到最好...也许有更优雅的方法,但它有效。它仍然非常粗糙和前卫,并且不考虑在第一个截断字符串末尾附近有“&”的文本。但只是给你一个想法。希望变量名能帮助你弄明白。希望对你有帮助,祝你好运...

$text = "long string with more than x characters ends j&aacute long stri";
$maxDisplayableLength = 51; // Would cut in j&acute in half!!!

$partOne = substr($text, 0, $maxDisplayableLength);
$partTwo = substr($text, $maxDisplayableLength, (strlen($text)-$maxDisplayableLength));
// Now go back max 8 positions (longest &-code)
$inspectLastEightChars  = substr($partOne, -8, 8);
$positionAmpersand      = stripos( $inspectLastEightChars, "&");
if ($positionAmpersand !== false) { // Ohoh, '&' is found
   $correctedPartOne = substr($partOne, 0, (strlen( $partOne ) - 8 + $positionAmpersand));
   $prePendToPartTwo = substr( $inspectLastEightChars, $positionAmpersand, (strlen($inspectLastEightChars)-$positionAmpersand));
   $correctedPartTwo = $prePendToPartTwo.$partTwo;
}
echo('$correctedPartOne: '.$correctedPartOne.'<br />'.'$correctedPartTwo: '.$correctedPartTwo.'<br />'.'Combined: '.$correctedPartOne.$correctedPartTwo);

结果:

$correctedPartOne: long string with more than x characters ends j
$correctedPartTwo: á long stri
Combined: long string with more than x characters ends já long stri