我有一张桌子,我想要限制可以显示的单词数量,在200个单词之后,如果可以的话......那会很棒,但那真是一个额外的好处。下面是收集从数据库中的内容的代码:字数截止
<tbody>
<?php
// table content:
$i = 0;
if (is_array($this->users) && count($this->users) > 0) {
foreach ($this->users as $userIdx => $user) {
$class = "sectiontableentry" . (1 + ($i % 2)); // evenodd class
if ($this->allow_profilelink) {
$style = "style=\"cursor:hand;cursor:pointer;\"";
$style .= " id=\"cbU".$i."\"" ;
} else {
$style = "";
}
if ($user->banned) {
echo "\t\t<tr class=\"$class\"><td colspan=\"".$colsNbr."\" ><span class=\"error\" style=\"color:red;\">"._UE_BANNEDUSER." ("._UE_VISIBLE_ONLY_MODERATOR.") :</span></td></tr>\n";
}
echo "\t\t<tr class=\"$class\" ".$style.">\n";
foreach (array_keys($this->columns) as $colIdx) {
echo "\t\t\t<td valign=\"top\" class=\"cbUserListCol" . $colIdx . "\">" . $this->_getUserListCell($this->tableContent[$userIdx][$colIdx]) . "\t\t\t</td>\n";
}
echo "\t\t</tr>\n";
$i++;
}
} else {
echo "\t\t<tr class=\"sectiontableentry1\"><td colspan=\"".$colsNbr."\">"._UE_NO_USERS_IN_LIST."</td></tr>\n";
}
?>
</tbody>
,我想限制字的量列是类= cbUserListCol。
干杯。
这里是更新的版本似乎仍然没有限制的话:
<?php
function truncateWords($text, $maxLength = 200)
{
// explode the text into an array of words
$wordArray = explode(' ', $text);
// do we have too many?
if(sizeof($wordArray) > $maxLength)
{
// remove the unwanted words
$wordArray = array_slice($wordArray, 0, $maxlength);
// turn the word array back into a string and add our ...
return implode(' ', $wordArray) . '…';
}
// if our array is under the limit, just send it straight back
return $text;
}
// table content:
$i = 0;
if (is_array($this->users) && count($this->users) > 0) {
foreach ($this->users as $userIdx => $user) {
$class = "sectiontableentry" . (1 + ($i % 2)); // evenodd class
if ($this->allow_profilelink) {
$style = "style=\"cursor:hand;cursor:pointer;\"";
$style .= " id=\"cbU".$i."\"" ;
} else {
$style = "";
}
if ($user->banned) {
echo "\t\t<tr class=\"$class\"><td colspan=\"".$colsNbr."\" ><span class=\"error\" style=\"color:red;\">"._UE_BANNEDUSER." ("._UE_VISIBLE_ONLY_MODERATOR.") :</span></td></tr>\n";
}
echo "\t\t<tr class=\"$class\" ".$style.">\n";
foreach (array_keys($this->columns) as $colIdx) {
echo "\t\t\t<td valign=\"top\" class=\"cbUserListCol" . $colIdx . "\">" . ($this->_getUserListCell($this->tableContent[$userIdx][$colIdx])). "\t\t\t</td>\n";
}
echo "\t\t</tr>\n";
$i++;
}
} else {
echo "\t\t<tr class=\"sectiontableentry1\"><td colspan=\"".$colsNbr."\">"._UE_NO_USERS_IN_LIST."</td></tr>\n";
}
?>
这称为截断。有很多关于使用PHP来做到这一点,包括这里在stackoverflow(http://stackoverflow.com/questions/965235/how-can-i-truncate-a-string-in-php)。如果你想在最后加上'...',你可以编写你的函数来检查事实上是否需要被截断,如果它确实需要,只需将字符串'...'添加到结尾。最好将它添加为“elipsis”的适当html实体“hellip”。 –
抱歉,双重评论;这是一个有用的链接,帮助我当我第一次有这个问题:http://www.the-art-of-web.com/php/truncate/ –
可能重复[如何显示从BIG字符串片段php?](http://stackoverflow.com/questions/6582994/how-to-display-a-snippet-from-a-big-string-in-php) – KingCrunch