从不同方面获取字符串的子字符串

时间:2012-11-03 04:46:58

标签: php

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

场景1:

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

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

场景2:

$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";

场景4:

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

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

请帮忙!谢谢。

对我的英语非常抱歉!

2 个答案:

答案 0 :(得分: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>';

,快速,棕色,狐狸

快速,棕色,狐狸,更多

快速的棕色狐狸,更多

快速的棕色狐狸,更多

答案 1 :(得分: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

此代码仅由我测试过。如果有任何错误或例外,请反馈。感谢。