Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

while总是进入死循环,直到报内存溢出

最近改动代码,在本地调试while总是进入死循环,直到报内存溢出,这段代码在服务器里运行的好好的,在本地总是进入死循环,大佬们帮忙看看,感觉while条件判断的值并没有随着循环获取新的值。

相关代码

public function tixingtext($string, $maxLength = 18, $start=0)
    {    
        // 获取字符串长度
        $strlen = mb_strlen($string,'utf8');
        $array = array();
        $html = '';
        while ($strlen > $maxLength) {
            //循环,根据字符串长度截取赋值给数组
            $array[] = mb_substr($string, $start, $maxLength, "utf8");
            //截取字符串后,重新赋值
            $string = mb_substr($string, $maxLength, $strlen, "utf8");
            //获取剩余的字符串长度,给while条件调用
            $strlen = mb_strlen($string,'utf8');
            //截取长度,每循环一次减2,给while条件调用
            if($maxLength < $strlen)$maxLength = $maxLength -2;
            //if($strlen<20)return $array[2];
        }

        foreach($array as $k => $v){
            $html .= '<div>'.$v.'</div>';
        }
        
        return $html;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$maxLength < 0 (为负数),终止循环就行了,否则 $strlen > $maxLength 始终成立,陷入了死循环。

public function tixingtext($string, $maxLength = 18, $start=0) {    
        // 获取字符串长度
        $strlen = mb_strlen($string,'utf8');
        $array = array();
        $html = '';
        while ($strlen > $maxLength) {
            //循环,根据字符串长度截取赋值给数组
            $array[] = mb_substr($string, $start, $maxLength, "utf8");
            //截取字符串后,重新赋值
            $string = mb_substr($string, $maxLength, $strlen, "utf8");
            //获取剩余的字符串长度,给while条件调用
            $strlen = mb_strlen($string,'utf8');
            //截取长度,每循环一次减2,给while条件调用
            if($maxLength < $strlen)$maxLength = $maxLength -2;
            if ($maxLength < 0) break;
        }

        foreach($array as $k => $v){
            $html .= '<div>'.$v.'</div>';
        }
        
        return $html;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...