Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8328541
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T01:28:44+00:00 2026-06-09T01:28:44+00:00

I am trying to read text from files in a directory and have it

  • 0

I am trying to read text from files in a directory and have it be displayed as description text below an image. I have been able to use the STRIPOS function to separate out each part of the text, except am having trouble with the last section. The last section is titled “Description:” and actually runs into multiple lines. I don’t know how to display more than just the line that reads “Description:”. I want to print from “Description:” to the end of the file. I will post my code and the text file in this message.

$dirname = 'data';

$dirhandle = opendir($dirname);

$housestextarray = array();

if ($dirhandle)
        {
            while (false !==($file = readdir($dirhandle)))
            {
                if ($file !='.' && $file !='..')
                {
                    array_push($housestextarray, $file);
                }
            }

            closedir($dirhandle); 
        }

    sort($housestextarray);


    foreach ($housestextarray AS $housedescription)
        {
            $housetext = '';

            $description = '';

            $pos = stripos($housedescription, 'house_');

            if ($pos === false)
            {
                //nothing
            } else {
                    $lines_in_file = count(file($housedescription));

                    $fp=fopen($housedescription,"r");

                    for ($cntr = 1; $cntr <= $lines_in_file; $cntr++)
                {
                    $cityline=fgets($fp);
                    $priceline=fgets($fp);
                    $bedroomsline=fgets($fp);
                    $bathsline=fgets($fp);
                    $footageline=fgets($fp);
                    $realtorline=fgets($fp);
                    $grabberline=fgets($fp);

                    $descriptionline=fgets($fp);

                    //print $cityline;
                    //print $descriptionline;

                    //$housetext .= $line;

                    $citypos = stripos($cityline, 'City:');

                    if ($citypos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $city= $cityline."<br />\n";
                        //print $city;
                    } 

                    $pricepos = stripos($priceline, 'Price:');

                    if ($pricepos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $price = $priceline."<br />\n";
                        //print $price;
                    } 

                    $bedroomspos = stripos($bedroomsline, 'Bedrooms:');

                    if ($bedroomspos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $bedrooms = $bedroomsline."<br />\n";
                        //print $bedrooms;
                    } 

                    $bathspos = stripos($bathsline, 'Baths:');

                    if ($bathspos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $baths = $bathsline."<br />\n";
                        //print $baths;
                    } 

                    $footagepos = stripos($footageline, 'Footage:');

                    if ($footagepos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $footage = $footageline."<br />\n";
                        //print $footage;
                    } 

                    $realtorpos = stripos($realtorline, 'Realtor:');

                    if ($realtorpos === false)  //found the realtor line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $realtor = $realtorline."<br />\n";
                        //print $realtor;
                    } 

                    $grabberpos = stripos($grabberline, 'Grabber:');

                    if ($grabberpos === false)  //found the grabber line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $grabber_formatted = str_replace('Grabber:','', $grabberline);
                        $grabber = "<h3>".$grabber_formatted."</h3><br />\n";
                        //print $grabber;
                    } 

                    $descriptionpos = stripos($descriptionline, 'Description: ');
                                                                    if ($descriptionpos === false)  //found the description line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $description .= $descriptionline."<br />";

                        //print $description;

                    }
                }
                    $output = $grabber."<br/>".$city.$bedrooms.$baths;
                    $output .= $price.$footage.$realtor."<br />";
                    $output .= "<br />".$description."<br />";

                    print $output;

            }   

And here is the text file contents example (one of six files):

City: OceanCove
Price: $950,000
Bedrooms: 5
Baths: 3
Footage: 3000 sq. ft.
Realtor: Shirley Urkiddeng
Grabber: Fantastic Home with a Fantastic View!
Description:
You will never get tired of watching the sunset
from your living room sofa or the sunrise
from your back porch with a view overlooking
the gorgeous coral canyon. Once in a lifetime
opportunity!

UPDATED CODE WITH Branden’s help:

    function houseDescriptions()
{
    //$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
    //$dirname = $DOCUMENT_ROOT.'data';
$dirname = 'data';

$dirhandle = opendir($dirname);

$housestextarray = array();

if ($dirhandle)
        {
            while (false !==($file = readdir($dirhandle)))
            {
                if ($file !='.' && $file !='..')
                {
                    array_push($housestextarray, $file);
                }
            }

            closedir($dirhandle); 
        }

    sort($housestextarray);


    foreach ($housestextarray AS $housedescription)
        {
                        $housetext = '';

                        $description = '';

                        $data ="";

                        $pos = stripos($housedescription, 'house_');

                        if ($pos === false)
                        {
                            //nothing
                        } else {
                            $file_handle = fopen($housedescription, "r");
                    $data = "";
                    while (!feof($file_handle)) {
                       $filestrings .= fgets($file_handle);
                    }
                    fclose($file_handle);

                    //You'll need to double check the Regex if it doesn't work.
                    $data = preg_split('#\b(City:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)\b#', $filestrings);

                    $city = $data[0];
                    $bedrooms = $data[1];
                    $baths = $data[2];
                    $footage = $data[3];
                    $realtor = $data[4];
                    $grabber = $data[5];
                    $description = $data[6];                    
                    $output = $grabber."<br />".$city.$bedrooms.$baths;
                    $output .= $price.$footage.$realtor."<br />";
                    $output .= "<br />".$description."<br />";

                    print $output;

            }   

        }
        //return $output;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T01:28:46+00:00Added an answer on June 9, 2026 at 1:28 am

    Updated with proper regex

    fgets can have issues when trying to get a string out of text file, especially a long string, there may be a line break within it that you may not see in your text editing program. A better way to do this is to get all of the information from the text file and store it in a string, then handle all searches with preg_split(). This code below (assuming my regex is correct, you may need to recheck it) will get all of the variables from the text file for you.

    //Append the file location to the file name
    $housedescription = $dirname."/".$housedescription;
    
    //Get all contents of the file and save them into $filestrings
    $file_handle = fopen($housedescription, "r");
    $data = "";
    while (!feof($file_handle)) {
       $filestrings .= fgets($file_handle);
    }
    fclose($file_handle);
    
    //Remove any pesky \n newlines that were added by the text file
    $filestring = preg_replace("/[\n\r]/","",$filestrings); 
    
    //Case Sensitive Regex Search, split the string into an array based on the keywords
    $data = preg_split('/(City:|Price:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)/', $filestring, -1, PREG_SPLIT_NO_EMPTY);
    
    //Save all the keywords to vars
    $city = "City: ".$data[0];
    $bedrooms = "Bedrooms: ".$data[1];
    $baths = "Baths: ".$data[2];
    $footage = "Footage: ".$data[3];
    $realtor = "Realtor: ".$data[4];
    $grabber = "Grabber: ".$data[5];
    $description = "Description: ".$data[6];
    

    Notice the addition of $filestring = preg_replace("/[\n\r]/","",$filestrings); this will remove any extra new lines that were in the text file so there are no
    ‘s where you don’t want them.

    Of course the absolute ideal would be to store all of your data in a mysql database instead of .txt files, as it is more secure and much faster for data access. But if you prefer .txt try not to open the same file more than once.

    Some notes to take from this: How to use Regular Expressions, fopen, fgets, preg_replace, preg_split

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application that imports data read from text files from a directory
I'm trying to use MSBuild to read in a list of files from a
I'm trying to have python read some lines of text from a file and
I am Trying to read data from text files and save tokens in SQLite
i'm trying to read text from a text file that I have in my
I am trying to read a text file from raw folder, and it works
I'm trying to read values from a text file into a hashtable, I want
I am trying to read some info from a text file by using windows
I am trying to read values from a text file using the Qt code
I'm trying to read the last line from a text file. Each line starts

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.