在PHP中以所需方式读取和打印文件内容

问题描述 投票:0回答:2

我有文本文件($ test_filename),其中包含以下内容:

boy
girl
man
woman
child

我需要在PHP中读取此文本文件,并以下列方式将内容存储在字符串中:

$output = (type, 'child', 'woman', 'man', 'girl', 'boy')

我正在尝试使用以下代码,但我得到额外的报价和空格。

 $file = file_get_contents($test_filename);
 $revstr = "";
 $teststr = explode(" ",$file);
 for($i=count($teststr)-1;$i>=0;$i--){
      $revstr = $revstr.$teststr[$i]." ";
 }

 echo $revstr;

 $str = "'" . implode("','", explode(' ', $revstr)) . "'";

 echo $str;

 $output = "(type, $str)";    

 echo $output;  

我得到以下输出。每个单词前都有一个额外的空格(除了最后一个单词 - 男孩)。最后还有一个额外的逗号和双引号。

(type, ' child', ' woman', ' man', ' girl', 'boy','')

谁能帮助我获得所需的确切输出?

php string file-handling
2个回答
0
投票

你几乎就在那里,但如果你使用了更多PHP的内部功能,这将更加整洁。使用数组来存储值,而不是仅使用implodeexplode直接操作字符串,并单独处理每个步骤。它将使您的代码在未来更具适应性。

$test_filename = 'people.txt';

// Read the file into an array, ignoring line endings and empty lines
$lines = file($test_filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// Reverse the order
$people = array_reverse($lines);

// Surround each string in quotes
$quoted = array_map(function ($e) { return "'{$e}'"; }, $people);

// Build up a single comma-separated string
$str = implode(', ', $quoted);

// Create desired output format
$output = "(type, $str)";

// Display
echo $output;

(类型,'孩子','女人','男人','女孩','男孩')

如果你愿意,你可以明显地将它减少到更少的线。


0
投票

相反,使用file()返回一个数组,然后使用胶水包括间距内爆,然后只连接开始和结束。

<?php
$array = file($test_filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

echo "(type, '".implode("', '", $array)."')";

https://3v4l.org/fkuJo

结果:

(type, 'boy', 'girl', 'man', 'woman', 'child')

如果你想要它反转,使用array_reverse()

echo "(type, '".implode("', '", array_reverse($array))."')";

(type, 'child', 'woman', 'man', 'girl', 'boy')
© www.soinside.com 2019 - 2024. All rights reserved.