Formating a txt file

Viewed 45

I have a TXT file formatting that looks like:

123451234512345
123451234512345

I want to format the file with php in this format:.

12345-12345-12345
12345-12345-12345

This is what I have tried:

$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;
}
2 Answers

Try this,

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

print_r($arr);

Result:

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

If you want to echo the result then do <?= implode(PHP_EOL, $arr) ?>

Possible that if can be written shorter

$codes = "codes.txt";
$array = file($codes, FILE_IGNORE_NEW_LINES);
$p = "/([1-9]{5})([1-9]{5})([1-9]{5})/i";
$r = "${1}-${2}-${3}";

foreach ($array as $a) {
    echo preg_replace($p, $r, $a);
}
Related