【问题标题】:My script use more memory to run我的脚本使用更多内存来运行
【发布时间】:2013-02-16 16:02:40
【问题描述】:

我使用了一些代码来限制在 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% 的物理内存。

谁能告诉我这是什么原因?

谢谢。

【问题讨论】:

  • 听起来像是一个无限循环。您可以只计算空格数,可能在trim($subject) 之后,然后在退出或添加空格数(可能是添加)之后的子字符串。
  • 你能给我举个例子吗?谢谢
  • 你应该检查 if ($subject !== false)
  • 这可能是由于主题列表非常冗长(无论来自哪里),或者while 是一个无限循环(永远不会退出)。目前尚不清楚您想用$subject$position 做什么。您能否简要描述一下输出的含义?
  • 您没有处理$subjects 短于 70 个字符的情况(在这种情况下,您的代码会卡在while($subject !=" "))。

标签: php memory-leaks


【解决方案1】:

如果我理解正确,您希望返回字符串的前 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);

【讨论】:

  • 如果$pos === false,只返回截止点前最后一个空格的部分可能是合理的。
  • @TharangaNuwan 是的,我编辑了代码以在文本被截断时返回“...”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 2013-03-23
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
相关资源
最近更新 更多