首页 > 解决方案 > 如何使用 php 对 .txt 文件中的字符串进行排序?

问题描述

我想按字母顺序显示“单词”,但我遇到的所有解决方案示例都不适合我。

我尝试使用 implode() 和 explode() 函数,使用 file() 函数,然后使用 sort() 函数。

非常感谢任何帮助,谢谢!

<!DOCTYPE html>
<html>
  <head>
    <title>words list</title>
  </head>
  <body>
    <h1>Word List</h1> 
    <?php
      @$fp = fopen("words.txt", 'rb');
      flock($fp, LOCK_SH); // lock file for reading



      while (!feof($fp)) {
         $words= fgets($fp);
     explode($words, "\n");
         file($words);
         sort($words);

         echo htmlspecialchars($words)."<br />";
      }
      flock($fp, LOCK_UN); // release read lock

      fclose($fp); 
    ?>
  </body>
</html>

标签: phphtml

解决方案


<!DOCTYPE html>
<html>
  <head>
    <title>words list</title>
  </head>
  <body>
    <h1>Word List</h1> 
    <?php
    $lines = file("words.txt");
    print_r($lines);
    natsort($lines); // this will sort lines in your file
    print_r($lines);
    // This was optional here you can overwrite existing file or can create new file
    file_put_contents("newtime.txt", implode("\n", $lines)); 
    ?>
  </body>
</html>

我检查了一下,它对我有用!!!


推荐阅读