0

我正在尝试开发一个代码,该代码将按升序对文本文件的内容进行排序。我已经阅读了文件的内容并且能够显示文本。我很难将它们逐字逐句从低到高排序。

我已经尝试过来自 php.net 的 asort,但无法让代码正常工作。谢谢。

4

4 回答 4

0
//Split file by newlines "\n" into an array using explode()
$file = explode("\n",file_get_contents('foo.txt'));
//sort array with sort()
sort($file);
//Build string and display sorted contents.
echo implode("\n<br />",$file);

排序函数需要有一个数组作为参数,确保你的文件在一个数组中。asort用于关联数组,因此除非您需要保留可以使用的数组键sort

于 2013-04-25T11:14:03.013 回答
0

尝试这个

<?php
$filecontent = file_get_contents('exemple.txt');

$words = preg_split('/[\s,.;":!()?\'\-\[\]]+/', $filecontent, -1, PREG_SPLIT_NO_EMPTY);
$array_lowercase = array_map('strtolower', $words);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $words);


foreach($words as $value)
{
    echo "$value <br>";

}

?>
于 2013-04-25T10:24:29.740 回答
0
$file = "Hello world\ngoodbye.";

$words = preg_split("/\s+/", $file);
$clean_words = preg_replace("/[[:punct:]]+/", "", $words);

foreach ($clean_words as $key => $val) {
    echo "words[" . $key . "] = " . $val . "\n";
}

--output:--
words[0] = Hello
words[1] = world
words[2] = goodbye



sort($clean_words,  SORT_STRING | SORT_FLAG_CASE);

foreach ($clean_words as $key => $val) {
    echo "words[" . $key . "] = " . $val . "\n";
}

--output:--
words[0] = goodbye
words[1] = Hello
words[2] = world
于 2013-04-25T11:28:42.107 回答
0

要回答您的第二个问题,您可以将文本文件读入一个变量(就像您已经说过的那样),例如。$variable,然后使用explode(http://php.net/manual/en/function.explode.php)在每个空格处将每个单词分隔成一个数组:

//$variable is the content from your text file
$output = explode(" ",$variable); //explode the content at each space

//loop through the resulting array and output
for ($counter=0; $counter < count($output); $counter++) {

   echo $output[$counter] . "<br/>"; //output screen with a line break after each

} //end for loop

如果您的段落包含您不想输出的逗号等,您可以在爆炸之前替换变量中的那些。

于 2013-04-25T11:05:54.090 回答