简体   繁体   中英

PHP explode .txt file by new line and separator |

I have a log.txt file with these kind of datas:

2022-08-25 13:16----------817650|xx:xx:xx:xx:xx:xx|user1|10
2022-08-25 13:16----------817856|xx:xx:xx:xx:xx:xx|user1|5

I would like to compare the last values (10 and 5) from the last two lines, but I got stuck in recognizing the lines.

 <?php

    $textCnt  = "./log.txt";
    $contents = file_get_contents($textCnt);
    $arrfields = explode( "|" , $contents);
            
    
    echo $arrfields[3];

    ?>

I got this:

10 2022-08-25 13:16----------817856

instead of

10

This is a job for fgetcsv .

$fh = fopen('log.txt', 'r');

while(($currRow = fgetcsv($fh, null, '|')))
{
    echo $currRow[3].PHP_EOL;
}

If I am not mistake you can try use preg_match

$file = 'log.txt';

$text = file_get_contents($file);
preg_match_all('#\|(\d+)\n?#', $text, $mathches);

Result: Array ( [0] => 10 [1] => 5 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM