Heim  >  Artikel  >  Backend-Entwicklung  >  PHP用空格分割文本为数组的方法

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

巴扎黑
巴扎黑Original
2016-11-22 11:00:481524Durchsuche

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

文本文档text.txt内容:

1 字段1 字段2
2 字段1 字段2
3 字段1 字段2
4 字段1 字段2

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

$file = fopen("text.txt", "r") or exit("Unable to open file!");
while(!feof($file))
{
$arr = split(' ' , fgets($file));
print_r($arr);
}
fclose($file);
?>

 输出结果:

Array (
   [0] => 1
   [1] => 字段1
   [2] => 字段2

)
Array (
   [0] => 2
   [1] => 字段1
   [2] => 字段2

)
Array (
   [0] => 3
   [1] => 字段1
   [2] => 字段2

)
Array (
   [0] => 4
   [1] => 字段1
   [2] => 字段2
)

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

本php教程由JS代码站出品


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:php—Serializable接口Nächster Artikel:php—ArrayAccess接口