2

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;
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
OUD
  • 23
  • 4
  • What happens with this code? What should happen? – user3783243 Mar 26 '21 at 18:42
  • 4
    The second argument to [`str_split()`](https://www.php.net/manual/en/function.str-split.php) is an integer, not a string, and denotes the length of the chunks. So use `5` instead of `""`. In future questions you should include an example of what your code _actually_ does so we don't have to guess. – Sammitch Mar 26 '21 at 18:42
  • Oh sorry my bad i missed it, but iit just return NULL – OUD Mar 26 '21 at 18:45
  • 1
    In PHP < 8 this would also have generated a warning, turn `error_reporting` on/up. In >= 8 it's throws a TypeError. – Sammitch Mar 26 '21 at 18:49

2 Answers2

2

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) ?>

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

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);
}