1.implode(将数组元素组合成字符串)
$file = ''/tmp/httpProxyLog.csv'';
$arr = array('qq','ww','1.1',"","");
$arr = array_filter($arr);//过滤掉多余的空格元素;
$str = implode(",",$arr);//将数组以逗号组合成字符串。
exec("echo \"$str\" >> \"$file\"","",true);//将字符串追加到文件中;
$fp = fopen($file, 'w');
fputcsv($fp,$arr); //fputcsv()可以用数组循环的方式进行实现,写入csv文件
fclose($fp);
2.explod(把字符串打散为数组)
$str = "Hello world I love Shanghai";
$str = preg_replace("/\s(?=\s)/"
,
"\\1",
$str);//去掉多余的空格,只留一个空格;
$arr = explode(" ",$str);//然后以空格分割成数组;
echo $arr ;
或者
$str = "Hello world I love Shanghai"; $arr = explode(" ",$str);//然后以空格分割成数组;
$arr = array_filter($arr);//过滤掉多余的空格;
echo $arr;
3.文件修改
$filename = "/tmp/conntrack";
$line = 5;//修改的行数
//要替换的参数
$replace['search'] = "a";
$replace['replace'] = "b";
$fp=fopen($filename,'r+');
$result="";
if($fp){
$i=0;
while($str=fgets($fp)){
$i++;
if($i==$line){
$str=str_replace($replace['search'],$replace['replace'],$str);
}
$result.=$str;
}
file_put_contents($filename,$result);
fclose($fp);
}
4.将数组元素写入文件
$file_path = '3.txt';
$con_array = array(array('tcp','close','1.1.1.1'),array('tcp','close','1.1.1.2'));
foreach($con_array as $conntrack){
$con = implode(" ", $conntrack);//组合回字符串
file_put_contents($file_path, $con.PHP_EOL,FILE_APPEND);
}