PHP警告:str_repeat():第二个参数必须大于或等于0 [关闭]

I'm getting this in my php-error log, im not sure where $pad is being set:

PHP Warning: str_repeat(): Second argument has to be greater than or equal to 0 in file.php on line 105

Here is the code:

    $tokens = array_filter(array_map('trim', explode("
", $xml)));

    $result     = ''; // holds formatted version as it is built
    $pad        = 0; // initial indent
    $matches    = array(); // returns from preg_matches()

    $insideCDATA = false;
    $currentCDATA = null;

    foreach($tokens as $token) {
        $closeCDATA = false;

        if (preg_match('/^<!\[CDATA.*\]\]>$/', $token, $matches)) :
            $indent = 0;
        elseif (preg_match('/^<!\[CDATA.*$/', $token, $matches)) :
            $insideCDATA = true;
            $currentCDATA = '';
        elseif (preg_match('/.+\]\]>$/', $token, $matches)) :
            $insideCDATA = false;
            $closeCDATA = true;
            $indent = 0;
        elseif (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) : 
            $indent = 0;
        elseif (preg_match('/^<\/\w/', $token, $matches)) :
            if (!$insideCDATA) {
                $pad--;
            }
            $indent = 0;
        elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :
            $indent = 1;
        else :
            $indent = 0; 
        endif;

        if ($insideCDATA) {
            $currentCDATA .= $token;
        } else {
            if ($closeCDATA) {
                $token = $currentCDATA.$token;
                $currentCDATA = null;
            }
            $line    = str_repeat("\t", $pad).$token;
            $result .= $line . "
"; // add to the cumulative result, with linefeed
            $pad    += $indent; // update the pad size for subsequent lines    
        }
    }

    return $result;

You should make your code more stable, checking parameters prior to passing it to function. In your case you initialize $pad with zero, but then you can decrement this value and your second param to str_repeat can be less then zero.

For example, in this case you can call str_repeat in this manner str_repeat( "\t", ($pad >=0) ? $pad : 0 )

if ($insideCDATA) {
    $currentCDATA .= $token;
} else {
    if ($closeCDATA) {
        $token = $currentCDATA.$token;
        $currentCDATA = null;
    }
    $line    = str_repeat( "\t", ($pad >=0) ? $pad : 0 ).$token;
    $result .= $line . "
"; // add to the cumulative result, with linefeed
    $pad    += $indent; // update the pad size for subsequent lines