Home  >  Article  >  Backend Development  >  PHP用空格分割文本替数组的方法

PHP用空格分割文本替数组的方法

WBOY
WBOYOriginal
2016-06-13 12:43:41804browse

PHP用空格分割文本为数组的方法

php逐行读取文本文件,然后处理空格分隔文本,输出为数组的方法。

文本文档text.txt内容:

<span style="color: #000000;">1 字段1 字段2 
2 字段1 字段2 
3 字段1 字段2 
4 字段1 字段2 </span>

文本和文本之间用空格隔开,用php经过处理,输出为数组,一下是代码

<span style="color: #000000;">php 
</span><span style="color: #800080;">$file</span> = <span style="color: #008080;">fopen</span>("text.txt", "r") or <span style="color: #0000ff;">exit</span>("Unable to open file!"<span style="color: #000000;">); 
</span><span style="color: #0000ff;">while</span>(!<span style="color: #008080;">feof</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">))   
{   
    </span><span style="color: #800080;">$arr</span> = <span style="color: #008080;">split</span>(' ' , <span style="color: #008080;">fgets</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">)); 
    </span><span style="color: #008080;">print_r</span>(<span style="color: #800080;">$arr</span><span style="color: #000000;">); 
} 
</span><span style="color: #008080;">fclose</span>(<span style="color: #800080;">$file</span><span style="color: #000000;">); 
</span>?> 

?输出结果:

<span style="color: #0000ff;">Array</span><span style="color: #000000;"> 
( 
    [</span>0] => 1<span style="color: #000000;"> 
    [</span>1] =><span style="color: #000000;"> 字段1 
    [</span>2] =><span style="color: #000000;"> 字段2 
 
) 
</span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> 
( 
    [</span>0] => 2<span style="color: #000000;"> 
    [</span>1] =><span style="color: #000000;"> 字段1 
    [</span>2] =><span style="color: #000000;"> 字段2 
 
) 
</span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> 
( 
    [</span>0] => 3<span style="color: #000000;"> 
    [</span>1] =><span style="color: #000000;"> 字段1 
    [</span>2] =><span style="color: #000000;"> 字段2 
 
) 
</span><span style="color: #0000ff;">Array</span><span style="color: #000000;"> 
( 
    [</span>0] => 4<span style="color: #000000;"> 
    [</span>1] =><span style="color: #000000;"> 字段1 
    [</span>2] =><span style="color: #000000;"> 字段2 
) </span>

这样就实现了PHP用空格分割文本为数组的方法

本php教程由JS代码站出品

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