我熟悉PHP根据达到的最大字符数截断文本,但是我希望从字符中调整它以将文本限制为10行,然后再截断它。
我怎样才能实现这个目标?
以下是我目前用来限制字符数的内容:
<?php $str = $profile['bio'];
$max = 510;
if(strlen($str) > $max) {
$str = substr($str, 0, $max) . '...'; } ?>
<?php echo $str ?>
答案 0 :(得分: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);
?>
答案 1 :(得分:1)
我认为最好的办法是使用纯CSS来限制文本/容器的高度。
什么是文本的“线”? 纯文字写在表格字段中? 来自编辑器的文本可能里面装满了html标签? Utf8带外来字符的文字?
我没有看到短语“文本行”的常见模式,以便使用任何方法来限制其长度(因此它的高度)。
如果您仍想用php限制它,那么我建议使用长度限制器。一般来说,这里和网上都有无数的帖子。但是你应该小心编码数据(非拉丁语)
答案 2 :(得分:0)
e.g。
<?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,
答案 3 :(得分:-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...