1

我熟悉基于达到的最大字符数的 PHP 截断文本,但是我想在截断之前从字符中调整它以将文本限制为 10 行。

我怎样才能实现这一目标?

这是我目前用来限制字符数的方法:

<?php $str = $profile['bio'];
$max = 510;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...'; } ?>
<?php echo $str ?> 
4

4 回答 4

2

用于explode()将文本转换为行数组,array_slice()以限制行数,然后implode()将它们重新组合在一起:

<?php
    $text = "long\nline\ntext\nhere";
    $lines = explode("\n", $text);

    $lines = array_slice($lines, 0, 10); //10 is how many lines you want to keep
    $text = implode("\n", $lines);
?>
于 2013-04-16T13:09:53.643 回答
1

我认为你最好的选择是使用纯 CSS 来限制你的文本/容器的高度。

什么是文本“行”?纯文本写在表单域中?来自编辑器的文本可能里面充满了 html 标签?带有外来字符的utf8文本?

我没有看到短语“文本行”的共同模式,以便使用任何方法来限制其长度(因此限制其高度)。

如果你仍然想用 php 限制它,那么我建议使用长度限制器。总的来说,这里和网络上有无数的帖子。但是你应该小心编码数据(非拉丁数据)

于 2013-04-16T13:26:04.933 回答
0

例如

<?php
$subject = data();

$p = "![\r\n]+!";
$subject = preg_split($p, $subject, 11);
$subject = array_slice($subject, 0, 10);
echo join("\r\n", $subject);

function data() {
    return <<< eot
Mary had a little lamb,
whose fleece was white as snow.

And everywhere that Mary went,
the lamb was sure to go.

It followed her to school one day
which was against the rule.

It made the children laugh and play,
to see a lamb at school.

And so the teacher turned it out,
but still it lingered near,

And waited patiently about,
till Mary did appear.

"Why does the lamb love Mary so?"
the eager children cry.

"Why, Mary loves the lamb, you know."
 the teacher did reply.
eot;
}   

印刷

Mary had a little lamb,
whose fleece was white as snow.
And everywhere that Mary went,
the lamb was sure to go.
It followed her to school one day
which was against the rule.
It made the children laugh and play,
to see a lamb at school.
And so the teacher turned it out,
but still it lingered near,
于 2013-04-16T13:11:15.250 回答
-1

您可以使用此功能:

<?php
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function truncateLongText ($string, $limit, $break=".", $pad="...") {
    // return with no change if string is shorter than $limit
    $string = strip_tags($string, '<b><i><u><a><s><br><strong><em>');

    if(strlen($string) <= $limit)
        return $string;
    // is $break present between $limit and the end of the string?
    if ( false !== ($breakpoint = strpos($string, $break, $limit)) ) {
        if($breakpoint < strlen($string) - 1) {
            $string = substr($string, 0, $breakpoint) . $pad;
        }
    }
    return $string;
}

示例用法:

$text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
echo truncateLongText($text, 10);
// Lorem Ipsum is simply dummy text of the printing and typesetting industry...
于 2013-04-16T13:09:14.523 回答