我在我的php错误日志中得到这个,我不确定$ pad的设置位置:
PHP警告:str_repeat():第二个参数必须大于或 在第105行的file.php中等于0
以下是代码:
$tokens = array_filter(array_map('trim', explode("\n", $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 . "\n"; // add to the cumulative result, with linefeed
$pad += $indent; // update the pad size for subsequent lines
}
}
return $result;
答案 0 :(得分:3)
您应该使代码更稳定,在将参数传递给函数之前检查参数。在你的情况下,你用零初始化$pad
,但是你可以减少这个值,你的第二个参数str_repeat可以小于零。
例如,在这种情况下,您可以通过str_repeat
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 . "\n"; // add to the cumulative result, with linefeed
$pad += $indent; // update the pad size for subsequent lines