可能重复:
How to get first x chars from a string, without cutting off the last word?
php trim a string
我的问题是我需要将一个字符串剪切成少于30个字符,同时还要确保字符串完成一个单词。
我一直在用这个:
$slidedescription = substr($slidedescription,0,30).'...';
问题是它可以切入字符串中间字。有没有简单的方法来确保它完成一个单词,但它长度少于30个字符?
答案 0 :(得分:1)
我试图覆盖尽可能多的意外情况:
<?
$string_1 = "anavaragelongword shortword";
$string_2 = "averylongwordwhichisprobablymorethan30characters word1";
$string_3 = "word2 word3 averylongwordwhichisprobablymorethan30characters";
$string_4 = "three avarege words";
$char_length = 30;
echo slidedescription($string_1, $char_length);
echo slidedescription($string_2, $char_length);
echo slidedescription($string_3, $char_length);
echo slidedescription($string_4, $char_length);
function slidedescription($string, $char_length)
{
$total_length = null;
$slidedescription = null;
$length = strlen($string);
if($length>$char_length) {
$array = explode(" ", $string);
foreach ($array as $key => $value) {
$value_length[$key] = strlen($value);
$total_length = $total_length + $value_length[$key];
if ($total_length<=$char_length) {
$slidedescription .= $value." ";
}
if (!$slidedescription) {
$slidedescription = substr($value,0,$char_length).'...';
}
}
} else {
$slidedescription = $string;
}
$last = trim($slidedescription).'... <br />';
return $last;
}
答案 1 :(得分:0)
您可以尝试使用
查找空格发生的最后位置 你可以像这样使用它:$spacelocation = strrpos($slidedescription, " ");
if($spacelocation != false)
{
if($spacelocation < 30)
{
$slidedescription = substr($slidedescription,0,$spacelocation).'...';
}
}
else
{
$slidedescription = substr($slidedescription,0,30).'...';
}