将文本限制为仅两行

新手上路,请多包涵

我想将 html 电子邮件中 150px 宽度的表格的文本限制为固定行数,例如:

 Long text continues down the road into a lane and doesn't stop there

我希望它看起来像这样:

 Long text continues down
the road into a lane and...

我将字符串截断最多 45 个字符,包括省略号,但有时当出现长单词时,它会变成三行:

 Long text continues at
accelerating speed into the
road...

理想情况下,我想打破加速这个词,或者宁愿在第一行填充尽可能多的字符,然后继续到第二行,有没有办法在 html 中做到这一点? (我查看了自动换行,但显然并非所有电子邮件客户端都支持它)

此外,由于这是电子邮件客户端,我也不能做任何 javascript 等。

原文由 Sainath Mallidi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
2 个回答

CSS 解决方案

您可以设置一个高度并隐藏溢出。

 span {
    display: inline-block;
    border: black 1px solid;
    width: 300px;
    height: 40px;
    overflow: hidden;
}

示例:http: //jsfiddle.net/imoda/REs2Q/


PHP解决方案

服务器端的替代方案是使用 substr

 <?php

    $string = "Oh squiggly line in my eye fluid. I see you lurking there on the peripheral of my vision. But when I try to look at you, you scurry away. Are you shy, squiggly line? Why only when I ignore you, do you return to the center of my eye? Oh, squiggly line, it's alright, you are forgiven.";

    echo charlimit($string, 100);

    function charlimit($string, $limit) {

        return substr($string, 0, $limit) . (strlen($string) > $limit ? "..." : '');
    }

?>

示例http ://codepad.org/OetkaMh6

这将输出字符串的 100 个字符,然后附加 ... 技巧是您必须将字符数更改为最适合您的情况。因为它是服务器端的,所以它不知道在每种情况下需要多少个字符才能触发一次回车。

或者,您可以限制字数:

 <?php

    $string = "Oh squiggly line in my eye fluid. I see you lurking there on the peripheral of my vision. But when I try to look at you, you scurry away. Are you shy, squiggly line? Why only when I ignore you, do you return to the center of my eye? Oh, squiggly line, it's alright, you are forgiven.";

    echo wordlimit($string, 20);

    function wordlimit($string, $limit) {

        $overflow = true;

        $array = explode(" ", $string);

        $output = '';

        for ($i = 0; $i < $limit; $i++) {

            if (isset($array[$i])) $output .= $array[$i] . " ";
            else $overflow = false;
        }

        return trim($output) . ($overflow ? "..." : '');
    }

?>

示例http ://codepad.org/WYJFPaD5

但都是一样的,你得裁剪到“最适合”

希望有所帮助。

原文由 Steve Robbins 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您的消息是一个字符串,您可以使用 PHP 执行以下操作:

 $stringChunkArray = str_split($string, 45); // 45 = desired char count
foreach ($stringChunkArray as $line) {
    echo $line.PHP_EOL;
}

这将保证每行 45 个字符……

原文由 Drew 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题