我在php中输出修改后的文件时遇到问题,这是我的代码:
<?php
$content = file_get_contents("1.txt");
$items = explode("\n",$content);
$line = "";
foreach ($items as $item){
$values = explode(",",$item);
foreach ($values as &$value){
$key = array_search($value,$values);
if ($key!=4){
$line .= $value.",";
}
elseif ($value=="0"){
$value="?";
$line .= $value."\n";
}
else $line .= $value."\n";
}
}
$file = fopen("1.txt","w");
fwrite($file,$line);
fclose($file);
?>
1.txt中的原始内容是
1,1,1,1,1
2,2,2,2,0
所需的输出是
1,1,1,1,1
2,2,2,2,?
但是,当我运行脚本时,我得到了这个:
1,1,1,1,1,2,2,2,2,?
,
我的剧本有什么问题?非常感谢!
答案 0 :(得分:2)
您没有正确连接\n
行。这是我的位修改功能:
$content = '1,1,1,1,1
2,2,2,2,0';
$lines = explode("\n", $content);
$modLines = array();
foreach ($lines as $line)
{
$values = explode(',', $line);
foreach($values as &$value)
{
# Do here what ever you want to
if($value == '0')
$value = '?';
}
$modLines[] = implode(',', $values);
}
$content = implode("\n", $modLines);
echo $content;
返回
1,1,1,1,1
2,2,2,2,?