1

さまざまな側面から最初の 25 文字を出力する文字列から部分文字列を取得する必要があります。ここで、部分文字列は、スペースではなくコンマ (,) のみを考慮する必要があります。

シナリオ 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";

助けてください!ありがとう。

私の英語で大変申し訳ありません!

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 に答える