M
M
Michael R.2020-05-18 14:51:15
PHP
Michael R., 2020-05-18 14:51:15

How to properly process the read data from a file?

Greetings!

I'm trying to extract the last digits of each line from the file with a regular program. As a result, I get only the numbers of the last line, and processing all previous terms returns an empty array. What is the problem?

file.txt

охрана труда	167 589
пожарная охрана	75 967
организация охраны	21 617

php
$file = fopen("./file.txt", "r");

while(!feof($file))
{
  $str = fgets($file);
  preg_match("/([0-9]+)?.([0-9]+)$/i", $str, $matches);
  print_r($matches);
}

fclose($file);

result
Array
(
)
Array
(
)
Array
(
    [0] => 21 617
    [1] => 21
    [2] => 617
)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
maddog670, 2020-05-18
@Mike_Ro

<?php

$file = fopen("./file.txt", "r");

$arr = [];

while(!feof($file))
{
  $buffer = fgets($file);

  preg_match('/\d+\s?\d+/', $buffer, $match);

  $arr[] = $match;
}

fclose($file);

print_r($arr);

E
Eugene, 2020-05-18
@Nc_Soft

Your example works correctly on a poppy for me, but it may not work on Windows. Try changing the regex to something like this

<?php
$file = fopen("./file.txt", "r");

while(!feof($file))
{
$str = fgets($file);
$matches = [];
preg_match("/\d+\s?\d+/", $str, $matches);
print_r($matches);
}

fclose($file);

upd. Yes, this is exactly the format of the end of the line;
you have the end of the line in win format, in fact, all lines except the last one look like this
охрана труда 167 589\r\n

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question