-1

I have a text file that looks like below:

enter image description here

Is there a way to echo particular characters only per line?

  • 29 characters that starts with "9954" value
  • Last 13 characters of the line

My code to display the text file:

<?php
header('Content-Type: text/html; charset=UTF-8');
echo "<pre>".file_get_contents("MAGFLE_Greenbnk_Caraga.txt")."</pre>";
?>

Your help will be very much appreciated
Thank You

Ryan Abarquez
  • 307
  • 2
  • 6
  • 16
  • How are those columns separated? With tabs? – Rizier123 Mar 29 '16 at 02:26
  • 1
    Use `file()` to read the file into an array of lines. Loop through the array, extracting the parts that you want using a regular expression. – Barmar Mar 29 '16 at 02:34
  • Or use a `while($line = fgets($fp))` loop to read one line at a time from the file, and then do the same thing. – Barmar Mar 29 '16 at 02:35
  • 1
    There must be hundreds of tutorials on how to read from a file in PHP. Please make some effort to learn on your own. – Barmar Mar 29 '16 at 02:36

2 Answers2

0

Use a multiline regular expression and loop over all matches:

$source = file_get_contents("MAGFLE_Greenbnk_Caraga.txt");
$matches = [];

preg_match_all("/(9954[0-9]{25}).*(.{13}$)/um", $source, $matches);

for($i = 0; $i < count($matches[1]); ++$i) {
    echo "Line {$i} -- ";
    echo "chars that start with '9954': {$matches[1][$i]} --- ";
    echo "last 13 chars: {$matches[2][$i]} <br>";
}

The regular expression contains two capture groups. The first group matches the 29 characters starting with '6654'. The second one matches the last 13 characters.

The matches array contains 3 arrays:

  • The first array contains all matched lines
  • The second array contains all matches from the first capture group
  • The third array contains all matches from the second capture group

I get the following output when applying your data:

result

Depending on your data this will not work in all cases. Maybe you have to enhance the regex with more rules.

tommy
  • 3,517
  • 18
  • 17
-2

You can store the .txt data in an array and then sort as you please. The explode() function should help. Link given below -

Reading text after a certain character in php

Community
  • 1
  • 1