0

いくつかのコードを使用して、whileループの段落からの文字の表示を制限しました。

これは私のコードです:

//mysqli_stmt_fetch ($stmt);    
while (mysqli_stmt_fetch($stmt)) {

      $position=70; // Define how many characters you want to display.      
      // Find what is the last character.
      $subject = substr($subjects,$position,1);

      if($subject !=" "){
         while($subject !=" "){
            $i=1;
            $position=$position+$i;
            $subject = substr($subjects,$position,1); 
         }
      }     
      $subject = substr($subjects,0,$position); 

      echo '<h4><span>Subjects / </span>'.$subject.'.....</h4>';   
}

私の問題は、このスクリプトを実行すると、実行に時間がかかることです。$ positionの値を小さくすると、スクリプトがすばやく実行され、$ positionの値を大きくすると、実行に時間がかかります。

それ$position=80が機能しない場合。実際にはまったく実行されていません。私のWindowsタスクマネージャは、物理メモリを100%使用していると表示します。

誰かがこれの理由を教えてもらえますか?

ありがとうございました。

4

1 に答える 1

3

私が正しく理解している場合、文字列の最初の 70 文字を返したいと考えていますが、最初のスペース文字で切り捨てます。

これを使用できます:

function get_snippet($subject, $count) {

    // if string length is already under the desired char count
    if (strlen($subject) <= $count) return $subject;

    // find first space char after desired position
    $pos = strpos($subject, ' ', $count);

    if ($pos === false) return $subject;   // no space, must be end of the string so return entire text
    else return substr($subject, 0, $pos) . '...'; // return all chars up to first space
}

それを呼び出す:

$newtext = get_snippet($subjects, 70);
于 2013-02-16T16:44:08.487 に答える