PHP代码 - 截断不工作

时间:2013-06-15 00:46:57

标签: php

以下是我在内部网络服务器上运行的HTML代码。我无法弄清楚如何让PHP截断从DB返回的文本正常工作:

编辑:这是我看到的(想要25个字符,然后是省略号)

enter image description here

<html>
<head><title>My Title</title>

<?php
    function truncate($text, $chars = 25) 
    {
        $text = $text." ";
        $text = substr($text,0,$chars);
        $text = substr($text,0,strrpos($text,' '));
        $text = $text."...";
        return $text;
    }
?>

</head>
<body>
<div id="mydiv">
    <table class="myTable">
        <tr>
            <td>Col 1</td>
        </tr>
        <?php
        $counter = 0;
        while ($counter < $numRows)
        {
            $f3=mysql_result($result,$counter,"url");
        ?>
        <tr>
            <td>
                <div class="masker">
                    <a href="<?php echo $f3; ?>" target="_blank"><?php echo truncate($f3); ?></a>
                </div>
            </td>
        </tr>
        <?php
            counter++;
        ?>
    </table>
</div>
</body>
</html>

有什么想法吗?感谢。

3 个答案:

答案 0 :(得分:3)

echo truncate(echo $f3);应为echo truncate($f3);

答案 1 :(得分:1)

尝试使用CSS:

,而不是截断字符串
.someClass {
    display:inline-block;
    max-width:150px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}

HTML:

<a href="..." target="_blank" class="someClass"><?=$f3?></a>

话虽如此,如果你的$f3是一个网址,它不应该有任何空格,所以你不应该用你的功能修剪它......

答案 2 :(得分:0)

function shorter($input, $length)
{
    //no need to trim, already shorter than trim length
    if (strlen($input) <= $length) {
        return $input;
    }

    //find last space within length
    $last_space = strrpos(substr($input, 0, $length), ' ');
    if(!$last_space) $last_space = $length;
    $trimmed_text = substr($input, 0, $last_space);

    //add ellipses (...)
    $trimmed_text .= '...';

    return $trimmed_text;
}
?>