如何在PHP中读取文件时使用2个分隔符

时间:2016-06-21 09:57:49

标签: php file

我正在尝试创建一个在线测验网络应用程序,并且我坚持阅读带有questions.enter代码的文件。这是文件:

@$!#include<stdio.h>
void main()
{
printf();
scanf();
}
@$!#include<stdio.h>
void main()
{  
printf();
scanf();
}
@$!#include<stdio.h>
void main()
{
printf();
scanf();
}

所以我必须从@ $阅读!到下一个@ $!同时也应保持新的线序列。我的PHP代码看起来像这样

<?php
$filename = "newfile.txt";
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));
fclose ($fd); 
$delimiter = "\n";
$splits= explode($delimiter, $contents);
foreach ( $splits as $show )
{

$ctr = explode("@$!",$show);
foreach($ctr as $nl)
echo $nl;

} 


 ?>

输出如下:

   #include void main() { printf(); scanf(); } #include void main() {   
   scanf(); } #include void main() { printf(); scanf(); } 

一条直线。我错过了什么吗?或者还有另一种方法吗?

1 个答案:

答案 0 :(得分:2)

<?php
$filename = "update.txt";
$contents =  nl2br(file_get_contents($filename));
?>

请你用它来阅读文件吗?

<强>结果:

@$!#include
void main()
{
printf();
scanf();
}
@$!#include
void main()
{
printf();
scanf();
}
@$!#include
void main()
{
printf();
scanf();
} 

您修改过的代码:

<?php
$filename = "newfile.txt";
$contents =  nl2br(file_get_contents($filename));
$delimiter = "\n";
$splits= explode($delimiter, $contents);
foreach ( $splits as $show )
{

$ctr = explode("@$!",$show);
foreach($ctr as $nl)
echo $nl;

} 
?>

<强>结果:

#include
void main()
{
printf();
scanf();
}
#include
void main()
{
printf();
scanf();
}
#include
void main()
{
printf();
scanf();
}