2

Есть txt файл в котором есть некий текст:

1
2 3
4 5
6 7
8 9

Нужно сделать так чтоб получилось:

1
2
3
4
5
6
7
8
9
1
  • 1
    В чем заключается вопрос?
    – Grundy
    26 фев 2017 в 21:16

3 ответа 3

3

Если за исходный файл принять file_1.txt, а за файл с результатом file_2.txt и речь идет о замене одного пробела, то можно так:

file_put_contents('file_2.txt', '');
foreach (file('file_1.txt') as $row) {
    file_put_contents('file_2.txt', str_replace(' ', "\n", $row), FILE_APPEND);
}
3

И я поучаствую:

$withSpaces = file_get_contents('source.txt');
$noSpaces = str_replace(' ', PHP_EOL, $withSpaces);
file_put_contents('dest.txt', $noSpaces);

Короче?

file_put_contents('dest.txt', str_replace(' ', PHP_EOL, file_get_contents('source.txt')));
1

Это совсем просто:

$handle = fopen("input.txt", "r");
$handle_w = fopen("output.txt", "w");
if ($handle) {
  while (($line = fgets($handle)) !== false) {
    $line = str_replace ( ' ' , "\n" , $line );
    fputs($handle_w, $line);
  }
  fclose($handle);
  fclose($handle_w);
} else {
  echo 'Ошибка чтения файла';
} 
1
  • 'Ошибка чтения файла' - а ошибка записи идёт лесом?)
    – Qwertiy
    26 фев 2017 в 23:04

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.