我正在建立一个关于健康的网站。我需要在表格中显示一些症状及其数据。但是,某些症状的名称太长,导致布局问题。所以,我找到了一种用 PHP 缩短名称的方法,如下所示:
<?=strlen($a)>45 ? stripslashes(substr($a, 0, 45)."...") : stripslashes($a)?>
工作正常。唯一的问题是当字符串在HTML Entity的中间被剪切时,会导致浏览器显示带有问号的菱形(http://prntscr.com/dzqyps)。
示例:
原始字符串:
超过x个字符的长字符串结束j&amp; aacute
截断字符串:
超过x个字符的长字符串结束j&amp; aa ...
浏览器中显示的字符串:
超过x个字符的长字符串结束j?...
我该如何解决这个问题?
答案 0 :(得分:0)
$text = "long string with more than x characters ends já long stri";
$maxDisplayableLength = 51; // Would cut in j´ 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