如何用PHP对带注释的.properties文件按字母排序?
PHP 实现带注释的.properties文件按配置项字母排序(保留注释与配置项关联)
需要对带有注释的.properties文件按配置项的键进行字母排序,要求注释始终紧跟对应的配置项上方。现有代码直接按行排序,导致注释和对应配置项位置错乱。
原文件与代码
原.properties文件内容
product.TRDMCL.shortdescription.listitem3=Rubber clip adapts to collar cms.tracker-comparison.seo.meta-title=Compare the Features of Alpha GPS Trackers # https://alpha.com/en/c/shipping-costs # # lh-check { max: 60 } cms.shipping-costs.seo.meta-title=Shipping Costs and Delivery for Alpha GPS Trackers jobs.open-positions.heading=Your career at Alpha team.section2-4.title=Marketing general.action.add-to-cart=Add to Cart # Button that links to https://my.alpha.com/#/activate/device navigation.header.activateTracker=Activate Tracker
原PHP代码
$content = file_get_contents('short_codes.properties'); $config_list = explode(PHP_EOL, $content); sort($config_list); $content=""; foreach ($config_list as $config) { $content.=$config.'<br>'; } echo ($content);
期望输出
# https://alpha.com/en/c/shipping-costs # # lh-check { max: 60 } cms.shipping-costs.seo.meta-title=Shipping Costs and Delivery for Alpha GPS Trackers cms.tracker-comparison.seo.meta-title=Compare the Features of Alpha GPS Trackers general.action.add-to-cart=Add to Cart jobs.open-positions.heading=Your career at Alpha # Button that links to https://my.alpha.com/#/activate/device navigation.header.activateTracker=Activate Tracker product.TRDMCL.shortdescription.listitem3=Rubber clip adapts to collar team.section2-4.title=Marketing
解决方案代码
$content = file_get_contents('short_codes.properties'); $lines = explode(PHP_EOL, $content); // 存储注释与对应配置项的分组,结构为 [['comments' => [], 'config' => '']] $configGroups = []; $currentComments = []; foreach ($lines as $line) { $trimmedLine = trim($line); // 跳过空行(需保留空行可调整此逻辑) if (empty($trimmedLine)) { continue; } // 收集注释行 if (str_starts_with($trimmedLine, '#')) { $currentComments[] = $line; } else { // 绑定注释与配置项为一组 $configGroups[] = [ 'comments' => $currentComments, 'config' => $line ]; // 重置注释收集器 $currentComments = []; } } // 兼容文件末尾未关联的注释(可选) if (!empty($currentComments)) { $configGroups[] = [ 'comments' => $currentComments, 'config' => '' ]; } // 按配置项键名排序 usort($configGroups, function($a, $b) { $keyA = explode('=', $a['config'], 2)[0] ?? ''; $keyB = explode('=', $b['config'], 2)[0] ?? ''; return strcasecmp($keyA, $keyB); }); // 拼接最终内容 $output = ''; foreach ($configGroups as $group) { // 输出注释 foreach ($group['comments'] as $comment) { $output .= $comment . PHP_EOL; } // 输出配置项 if (!empty($group['config'])) { $output .= $group['config'] . PHP_EOL; } // 组间添加空行(可选) $output .= PHP_EOL; } // 清理末尾多余空行 $output = rtrim($output, PHP_EOL); // 页面输出或写入文件 echo nl2br($output); // file_put_contents('sorted_short_codes.properties', $output);
逻辑说明
- 分组收集:遍历每行内容,注释行暂存,遇到配置项时将暂存注释与当前配置项绑定为一组,确保注释与配置项关联。
- 自定义排序:提取配置项的键名(
=前的部分),使用不区分大小写的字母排序规则对分组排序。 - 格式拼接:按排序后的分组依次输出注释和配置项,保证注释始终在对应配置项上方。
内容的提问来源于stack exchange,提问作者Muhammad Ateeb
相关产品推荐
相关产品推荐

