php - 如何使用 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>
解决方案
<!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>
我检查了一下,它对我有用!!!
推荐阅读
- javascript - js 随机播放对象数组,同时保留一些顺序
- r - 基于灵活子集/条件的跨数据帧的 R 函数
- python - C 到 Python 的转换
- unity3d - 如何从 HMS IAP 服务器端恢复 Non-Consumable IAP 服务?
- python - 使用 stop = 单元格的值在 Pandas 中对字符串列进行切片
- c# - C# LINQ 如何有效地处理空返回?
- node.js - 如何正确地从另一个 Lambda 调用 Lambda
- selenium-webdriver - browserstack_executor 操作列表在哪里?
- vulkan - 深度附件需要 VkSubpassDependency,但颜色附件不需要
- android - 在片段转换期间隐藏 BottomNavigationView