そのため、データベースからページ情報を取得する動的な 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 については何もエコーしません。
誰かがこの種のことを行うためのアイデアやより良い方法を持っている場合は、知っておいてください!