1

我需要从一个字符串中获取子字符串,它将从不同方面输出前 25 个字符。这里的子字符串应该只考虑逗号 (,) 而不是空格。

场景一:

$str = "the, quick, brown, fox";

$res = "the, quick, brown, fox";

场景二:

$str = "the, quick, brown, fox, jumps, over, the, lazy, dog!";

$res = "the, quick, brown, fox, more";

场景 3:

$str = "the quick, brown fox, jumps over, the lazy dog!";

$res = "the quick, brown fox, more";

场景四:

$str = "the quick brown fox, jumps over, the lazy dog!";

$res = "the quick brown fox, more";

请帮忙!谢谢。

非常对不起我的英语!

4

2 回答 2

1

全部 4 个场景测试

(假设逗号在前 25 个字符内)

function stringm($string, $length = 25){

   if(strlen($string) >= $length){
       $string = substr($string, 0, $length-1);
        $str_array = explode(",", $string);
        // add logics here to check array len if comma may not be within the first 25 characters 
        array_pop($str_array);
        $string = implode(",", $str_array)  . ', more';
   }

   return $string;
}


echo stringm('the, quick, brown, fox')  . '<br>';
echo stringm('the, quick, brown, fox, jumps, over, the, lazy, dog!')  . '<br>';
echo stringm('the quick, brown fox, jumps over, the lazy dog!')  . '<br>';
echo stringm('the quick brown fox, jumps over, the lazy dog!')  . '<br>';

的, 快速的, 棕色的, 狐狸

的, 快速的, 棕色的, 狐狸, 更多

敏捷的棕色狐狸,更多

敏捷的棕色狐狸,更多

于 2012-11-03T05:38:32.453 回答
0

好吧,我只是想出了一个解决方案。我不确定可行性,但它对我很有用。

方法:

function excerpt($string, $length = 25) {
$new_string = $string;

if(strlen($string) >= $length) {
    $new_string = "";
    $array = explode(',', $string);
    $current = 0;
    for($i = 0; $i < count($array); $i++) {
        $current+= strlen($array[$i])+1;
        if($current <= $length)
            $new_string.= $array[$i].",";
        else {
            $new_string.= " more";
            $i = count($array);
        }
    }       
}
return $new_string;

}

输入:

echo excerpt('the, quick, brown, fox').'<br>';
echo excerpt('the, quick, brown, fox, jumps, over, the, lazy, dog!').'<br>';
echo excerpt('the quick, brown fox, jumps over, the lazy dog!').'<br>';
echo excerpt('the quick brown, fox jumps over, the lazy dog!').'<br>';
echo excerpt('the quick brown fox, jum, ps, over, the lazy dog!').'<br>';

输出:

the, quick, brown, fox
the, quick, brown, fox, more
the quick, brown fox, more
the quick brown, more
the quick brown fox, jum, more

此代码仅由我测试过。如有错误或异常,请反馈。谢谢。

于 2012-11-03T10:19:41.200 回答