HY!我试图为长标题做一个摘录,但最后一句话不应该被削减。我已经阅读了这个问题的相关主题,但似乎它引用了另一个问题(在搜索结果上)。这是我现在的职能
function excerpt($title) {
$new = substr($title, 0, 27);
if (strlen($title) > 30) {
return $new.'...';
} else {
return $title;
}
}
答案 0 :(得分:3)
我修改了@mohd zubair khan的解决方案,以满足问题的要求。
问题在于缩短字符串而不将其从尾部切下。 这是我的代码。
function strWordCut($string,$length)
{
$str_len = strlen($string);
$string = strip_tags($string);
if ($str_len > $length) {
// truncate string
$stringCut = substr($string, 0, $length-15);
$string = $stringCut.'.....'.substr($string, $str_len-10, $str_len-1);
}
return $string;
}
答案 1 :(得分:2)
I was actually able to solve it with:
if (strlen($title) < 30) {
return $title;
} else {
$new = wordwrap($title, 28);
$new = explode("\n", $new);
$new = $new[0] . '...';
return $new;
}
答案 2 :(得分:2)
function strWordCut($string,$length,$end='....')
{
$string = strip_tags($string);
if (strlen($string) > $length) {
// truncate string
$stringCut = substr($string, 0, $length);
// make sure it ends in a word so assassinate doesn't become ass...
$string = substr($stringCut, 0, strrpos($stringCut, ' ')).$end;
}
return $string;
}
答案 3 :(得分:1)
这是一个可以执行您想要的功能,并且检查它的测试功能是按预期工作的。
function excerpt($title, $cutOffLength) {
$charAtPosition = "";
$titleLength = strlen($title);
do {
$cutOffLength++;
$charAtPosition = substr($title, $cutOffLength, 1);
} while ($cutOffLength < $titleLength && $charAtPosition != " ");
return substr($title, 0, $cutOffLength) . '...';
}
function test_excerpt($length) {
echo excerpt("This is a very long sentence that i would like to be shortened", $length);
echo "
";
echo excerpt("The quick brown fox jumps over the lazy dog", $length);
echo "
";
echo excerpt("nospace", $length);
echo "
";
echo excerpt("A short", $length);
echo "
";
}
test_excerpt(5);
test_excerpt(10);
test_excerpt(15);
test_excerpt(20);
test_excerpt(50);
输出 -
This is... The quick... nospace... A short... This is a very... The quick brown... nospace... A short... This is a very long... The quick brown fox... nospace... A short... This is a very long sentence... The quick brown fox jumps... nospace... A short... This is a very long sentence that i would like to be... The quick brown fox jumps over the lazy dog... nospace... A short...