Home  >  Article  >  Backend Development  >  文本处理 - PHP读写txt文件的问题

文本处理 - PHP读写txt文件的问题

WBOY
WBOYOriginal
2016-06-06 20:17:321415browse

代码如下:



四位.club 域名



/*
test.txt 文件内容为:

10ferents.club
1901.club
1992.club
288cash.club
2nd.club
365gold.club
3dscanning.club
406disco.club
99fitness.club
abuo9i8n3.club
abuo9i8n5.club
abur5t6b2.club
abut6y7n1.club
abut6y7n4.club
abut6y7n7.club
abuy7u8n6.club
1234.club
abcd.club

4.txt 只有:
abcd.club

正确的答案应该是:
1901.club
1992.club
1234.club
abcd.club
*/
$handle=fopen("test.txt","r");
while(!feof($handle)){
$str=fgets($handle);
if(stripos($str,".")==4){
file_put_contents("4.txt",$str);
}
}
?>




筛选域名用的,但是结果怎么只显示一行啊,用
echo $str."
\n";显示结果在正常的.

回复内容:

代码如下:



四位.club 域名



/*
test.txt 文件内容为:

10ferents.club
1901.club
1992.club
288cash.club
2nd.club
365gold.club
3dscanning.club
406disco.club
99fitness.club
abuo9i8n3.club
abuo9i8n5.club
abur5t6b2.club
abut6y7n1.club
abut6y7n4.club
abut6y7n7.club
abuy7u8n6.club
1234.club
abcd.club

4.txt 只有:
abcd.club

正确的答案应该是:
1901.club
1992.club
1234.club
abcd.club
*/
$handle=fopen("test.txt","r");
while(!feof($handle)){
$str=fgets($handle);
if(stripos($str,".")==4){
file_put_contents("4.txt",$str);
}
}
?>




筛选域名用的,但是结果怎么只显示一行啊,用
echo $str."
\n";显示结果在正常的.

这样:

<code>$str = fgets($handle); 
$str = trim($str);</code>

不知道的怎么解决的时候,请

<code>var_dump(stripos($str,"."));
</code>

看看是否是4

还有追加写入:

<code>file_put_contents("4.txt",$str, FILE_APPEND);</code>

写了个DEMO,用正则匹配的

<code>$str = '10ferents.club 
1901.club 
1992.club 
288cash.club 
2nd.club 
365gold.club 
3dscanning.club 
406disco.club 
99fitness.club 
abuo9i8n3.club 
abuo9i8n5.club 
abur5t6b2.club 
abut6y7n1.club 
abut6y7n4.club 
abut6y7n7.club 
abuy7u8n6.club 
1234.club 
abcd.club';
preg_match_all('/[0-9a-z-]{4}/', $str, $arr);
$string = implode("\n", $arr[0]);
file_put_contents('1.txt', $string);
</code>

截图:
文本处理 - PHP读写txt文件的问题


file_put_contents每次都会覆盖掉之前的,应该用fwrite追加写入

file_put_contents("4.txt",$str,FILE_APPEND);

fopen("test.txt","a")

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn