php:达到行数后截断文本?

php:达到行数后截断文本?,php,Php,我熟悉PHP根据所达到的最大字符数来截断文本,但是我想在截断文本之前对字符数进行调整,将文本限制为10行 我怎样才能做到这一点呢 下面是我目前用来限制字符数的方法: <?php $str = $profile['bio']; $max = 510; if(strlen($str) > $max) { $str = substr($str, 0, $max) . '...'; } ?> <?php echo $str ?> 您可以使用此功能: <?php /

我熟悉PHP根据所达到的最大字符数来截断文本,但是我想在截断文本之前对字符数进行调整,将文本限制为10行

我怎样才能做到这一点呢

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

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

您可以使用此功能:

<?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;
}
用于将文本转换为行数组,限制行数,然后将其重新组合在一起:

<?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);
?>

例如


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

什么是文本的“行”? 在表单字段中写入纯文本? 来自编辑器的文本可能里面满是html标记? 带外来字符的Utf8文本

我看不到“文本行”这一短语有一个共同的模式,以便使用任何方法来限制其长度(从而限制其高度)


如果您仍然想用php限制它,那么我建议使用长度限制器。这里和网上的帖子不计其数。但是您应该注意编码数据(非拉丁语数据)

一行有多长?如果你说的是在一个div内完成,你需要在客户端完成
<?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);
?>
<?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,