我有文本文件($ 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','')
有人可以帮助我获得所需的确切输出吗?
答案 0 :(得分:0)
相反,使用返回数组的file(),然后使用包含间距的胶水内爆,然后只连接开头和结尾。
<?php
$array = file($test_filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
echo "(type, '".implode("', '", $array)."')";
<强>结果:强>
(type, 'boy', 'girl', 'man', 'woman', 'child')
如果您想要颠倒,请使用array_reverse()
echo "(type, '".implode("', '", array_reverse($array))."')";
(type, 'child', 'woman', 'man', 'girl', 'boy')
答案 1 :(得分:0)
你几乎就在那里,但如果你使用更多PHP的内部功能,这将更加整洁。使用数组来存储值,而不是仅使用implode
和explode
直接操作字符串,并单独处理每个步骤。它将使您的代码在未来更具适应性。
$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;
(类型,&#39;孩子&#39;,&#39;女人&#39;男人&#39;,&#39;女孩&#39;男孩&#39; )
如果你愿意的话,你可以将它减少到更少的行。