TNK
TNK

Reputation: 4323

My script use more memory to run

I used some codes to limit displaying characters from a paragraph in a while loop.

This is my code:

//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>';   
}

My problem is when running this script it take long time to run. If I discrease $position's value then executing script quickly and if I increase $position's value it take long time to execute.

if its $position=80 I can't get it to work. Actually its not executing at all. My windows Task Manager display it is using Physical Memory 100%.

Can anybody tell me what is the reason for this?

Thank you.

Upvotes: 0

Views: 116

Answers (1)

Igor Jerosimić
Igor Jerosimić

Reputation: 13741

If I understand correctly you wish to return first 70 characters of string, but cut it off at the first space character.

You could use this:

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
}

Calling it:

$newtext = get_snippet($subjects, 70);

Upvotes: 2

Related Questions