1

そのため、データベースからページ情報を取得する動的な Web サイトを作成するときに、おそらくかなり一般的な問題に遭遇しています。フロント ページに、最新の 8 つのブログ/ストーリー投稿を表示するスライダーがあるとします。サーバーはそれぞれのタイトル、キャプション、およびテキスト フィールドを取得しますが、記事の全文をブラウザに返すのは無駄です。だから私が推測しているのは、再帰関数を使用してテキストフィールドを特定の文字数で切り取ることですが、私が間違っていることを理解できないようです。コードは次のとおりです。

$string = strip_tags("<p>Jackson expects to practice on Wednesday for the first time since getting hurt in a season-opening game agains the Chicago Bears. The teams medical advisor says his sprained ankle has healed fast then expected, although he warns to err on the side of caution.</p><p>Coach Andy Reid is optimistic he can get Jackson ready in time for next Monday's square off vs the Detroit Lions, though he states that he doesn't want to take the risk of loosing him for the start of the playoffs in 3 weeks.</p>");
$count = 0;

echo $string."<br />";

function trim_string($string, $max_length, $search_char){
    global $count;
    $pos = strripos($string, $search_char);
    $new_string = substr($string, 0, $pos);
    $length = strlen($new_string);  

    if($length > $max_length){      
        $count++;
        trim_string($new_string, 120, ' ');
    }else{
        return $new_string; 
    }   
}

$trimmed_string = trim_string($string, 120, ' ');

echo $count."<br />".substr_count($string, ' ')."<br />".$trimmed_string;

ご覧のとおり、デバッグしようとしています。Count は 67 を返し、元の発生回数は 86 であるため、機能していることはわかっていますが、$trimmed_string については何もエコーしません。

誰かがこの種のことを行うためのアイデアやより良い方法を持っている場合は、知っておいてください!

4

3 に答える 3

1

これは必ずしも再帰的である必要はありません。

function trim_string($string, $max_length, $search_char)
{
    $string = substr($string, 0, $max_length);
    $last_index = strrpos($string, $search_char);
    return substr($string, 0, $last_index);
}

それが基本的な考え方です。スペースなどではない場所を切り刻むと、最後に空白ができる可能性があります。

また、再帰を返す必要があるため、エコーしません。

if($length > $max_length){      
    $count++;
    return trim_string($new_string, 120, ' ');
}else{
    return $new_string; 
}  
于 2012-10-27T00:53:35.970 に答える
0

サイズについてはこれを試してください:

/**
* Keeps a (maximum or minimum) number of characters from a string.
* Will not break words in the process.
*
* If $RightBound === true the $Length is the maximum allowed.
* If $RightBound === false the $Length is the minimum allowed.
* 
* @param string $String
* @param int $Length
* @param bool $RightBound
* @return string
*/
function ChunkWordsByLength($String, $Length, $Bound = true){
    if(!is_string($String)){
        trigger_error('$String must be a string.', E_USER_WARNING);
        return false;
    }
    if(!is_numeric($Length) or (($Length = intval($Length)) < 1)){
        trigger_error('$Length must be a positive integer.', E_USER_WARNING);
        return false;
    }
    if(strlen($String) <= $Length){
        return $String;
    }
    if(($Bound !== 'left') and ($Bound !== 'right')){
        trigger_error('$Bound must be "left" or "right".', E_USER_WARNING);
    }
    if($Bound === 'right'){
        $Pattern = "^.{0,{$Length}}\\b";
    }else{
        $Pattern = "^.{{$Length}}.*?\\b";
    }
    return preg_match("~{$Pattern}~", $String, $Slices) ? trim($Slices[0]) : false;
}

/**
* Alias of ChunkWordsByLength($String, $Length, 'right').
* 
* @param string $String
* @param int $Length
* @return string
*/
function ChunkWordsByLengthMax($String, $Length){
    return ChunkWordsByLength($String, $Length, 'right');
}

/**
* Alias of ChunkWordsByLength($String, $Length, 'left').
* 
* @param string $String
* @param int $Length
* @return string
*/
function ChunkWordsByLengthMin($String, $Length){
    return ChunkWordsByLength($String, $Length, 'left');
}

RegExpを使用し、長さを最小または最大文字数に設定できます。かなり短いですが、私も使っているのでエラーチェックを追加しました。

  1. バウンドが「右」の場合、長さの直前になります。
  2. バウンドが「左」の場合、長さの直後で壊れます。

このように使用します:

var_dump(ChunkWordsByLengthMax($String, 120));
var_dump(ChunkWordsByLengthMin($String, 120));

それが役に立てば幸い。

于 2012-10-27T01:28:32.103 に答える
0

もし私があなただったら、再帰関数を実行するのではなく、これを実行する 単純な関数 を実行します

  • 爆発する " " はい、1 つのスペースです

  • 各文字列の文字を数えた後

    ..披露させて

    $array = expand(" ",$string); //まあ言ってみれば

    $max_length = 50; $output=""; foreach($array as $value ){ if(strlen($output.$value) > $max_length) break; そうでなければ $output.=$value; }

    エコー $出力;

どう思いますか ?

于 2012-10-27T00:58:24.313 に答える