PHP - Explode

15:52 / Comments (0) / by SeLaMbeR

The regular expression parameters such as \n or \t can be used as well as other strings as the delimeter which can be used to parse any given text files or downloaded web pages to read line by line.

An example may be considered as, name surname and phone numbers are written into a text file line by line and columns are seperated by tabs, can be exploded and read easily through the return and tab characters. After storing them in the array they can be manipulated or displayed in any other formats.

// Explode text file and store each row of the file into the array elements
function explodeRows($data) {
  $rowsArr = explode("\n", $data);
  return $rowsArr;

// Explode the columns according to tabs
function explodeTabs($singleLine) {
  $tabsArr = explode("\t", $singleLine);
  return $tabsArr;

// Open the text file and get the content
$filename = "phonebook.txt";
$handle   = fopen($filename, 'r');
$data     = fread($handle, filesize($filename));
$rowsArr  = explodeRows($data);

// Display content which is exploded by regular expression parameters \n and \t
for($i=0;$i<count($rowsArr);$i++) {
  $lineDetails = explodeTabs($rowsArr[$i]);
    echo "<br>Name : " . $lineDetails[0];
    echo "<br>Surname : " . $lineDetails[1];
    echo "<br>Tel Number : " . $lineDetails[2];
    echo "<br><br>";

phonebook.txt text file can be something like this;
name1    sname1    +905429998877
name2    sname2    +905429998876
name3    sname3    +905429998875

The output will be as follows;
Name : name1
Surname : sname1
Tel Number : +905429998877 

Name : name2
Surname : sname2
Tel Number : +905429998876 

Name : name3
Surname : sname3
Tel Number : +905429998875