我是编程的新手,试图学习PHP以及PHP和HTML之间的代码分离。
我想用数组($ list)中的值替换HTML文件($ replacehtml)中的某些单词。 HTML文件由一个表行组成,该表行包含3个要替换的值($ ip,$ date,$ browser)。我想多次打印同一行(每次都使用数组中的新值),直到已经打印了数组中的所有值。但是我的代码似乎一遍又一遍地打印出前三个值,我不确定为什么。我确定我错过了一些东西,希望能有所帮助。
$list = array('ip1', 'date1', 'browser1','ip2','date2','browser2');
$n = 0;
for ($i=0 ; $i < count($list)-1 ; $i++){
if($n > count($list)-1){
break;
}
$replacehtml = str_replace($ip, $list[$n], $replacehtml);
$n++;
$replacehtml = str_replace($date, $list[$n], $replacehtml);
$n++;
$replacehtml = str_replace($browser, $list[$n], $replacehtml);
$n++;
echo $replacehtml;
}
我得到以下输出:
ip1 date1 browser1
ip1 date1 browser1
虽然应该是:
ip1 date1 browser1
ip2 date2 browser2
为什么您定义变量$i
但从不使用它?然后,通过增加变量for
而不是使用有用的内置函数来复制$n
循环的功能。
要获得所需的输出,我将使用以下更简单的代码:
$list = array('ip1', 'date1', 'browser1','ip2','date2','browser2');
for ($i = 0; $i < count($list); $i += 3){
$replacehtml = str_replace($ip, $list[$i], $replacehtml);
$replacehtml = str_replace($date, $list[$i + 1], $replacehtml);
$replacehtml = str_replace($browser, $list[$i + 2], $replacehtml);
echo $replacehtml;
}
这应该可以实现您的预期输出。
除了重复循环,主要问题还在于覆盖要替换为的原始字符串...
$replacehtml = str_replace($ip, $list[$n], $replacehtml);
所以第二次进入循环时,$replacehtml
已经替换了所有值。
只需使用其他变量将值放入以及随后的替换中...
$newhtml = str_replace($ip, $list[$n], $replacehtml);
然后
$newhtml = str_replace($date, $list[$n], $newhtml);
等最后
echo $newhtml;