首页 > 解决方案 > 格式化txt文件

问题描述

我有一个 TXT 文件格式,如下所示:

123451234512345
123451234512345

我想用这种格式的php格式化文件:。

12345-12345-12345
12345-12345-12345

这是我尝试过的:

$codes = "codes.txt";
$unformatedCode = file($codes, FILE_IGNORE_NEW_LINES);
$abcd = "-";
foreach ($array as $value) {
    $text = (string)$unformatedCode;
    $arr = str_split($text, "");
    $formatedCode = implode("-", $arr);
    echo $formatedCode;
}

标签: phpfilestrsplittxt

解决方案


尝试这个,

<?php
$arr = array_map(
  fn($v) => implode('-', str_split($v, 5)), 
  file("codes.txt", FILE_IGNORE_NEW_LINES)
);

print_r($arr);

结果:

Array
(
    [0] => 12345-12345-12345
    [1] => 12345-12345-12345
)

如果要回显结果,请执行<?= implode(PHP_EOL, $arr) ?>


推荐阅读