I have implemented a php search function on a clients website. What I would like it to do is search for files within the website directory for specific pdf files.
However I can't seem to get it to work. If I type in "pdf" into the search box it returns all the files in the directory but if I put in a specific file name then it returns nothing.
Below is the php script I am using:
<?php
$my_server = "http://www.gwent.org".":".getenv("http://www.gwent.org_80");
$my_root = getenv("docroot/");
$s_dirs = array("");
$hits = null;
$full_url = $_SERVER['PHP_SELF'];
$site_url = eregi_replace('customer_information.php', '', $full_url);
$directory_list = array('sold_msds');
$s_files = ".pdf";
foreach($directory_list as $dirlist)
{
$directory_url = $site_url.$dirlist."/";
$getDirectory = opendir($dirlist);
while($dirName = readdir($getDirectory))
$getdirArray[] = $dirName;
closedir($getDirectory);
$dirCount = count($getdirArray);
sort($getdirArray);
for($dir=0; $dir < $dirCount; $dir++)
{
if (substr($getdirArray[$dir], 0, 1) != ".")
{
$label = eregi_replace('_', ' ', $getdirArray[$dir]);
$directory = $dirlist.'/'.$getdirArray[$dir]."/";
$complete_url = $site_url.$directory;
if(is_dir($directory))
{
$myDirectory = opendir($directory);
$dirArray = null;
while($entryName = readdir($myDirectory))
$dirArray[] = $entryName;
closedir($myDirectory);
$indexCount = count($dirArray);
sort($dirArray);
}
else
{
$hits++;
if(file_exists($dirlist."/".$label))
{
$fd=fopen($dirlist."/".$label, "r");
$text=fread($fd, 50000);
$keyword_html = htmlentities($keyword);
if(!empty($keyword))
{
$do=stristr($text, $keyword) || stristr($text, $keyword_pdf);
}
if($do)
{
$strip = strip_tags($text);
$keyword = preg_quote($keyword);
$keyword = str_replace("/","\/","$keyword");
$keyword_html = preg_quote($keyword_html);
$keyword_html = str_replace("/","\/","$keyword_html");
echo "<span>";
if(preg_match_all("/((\s\S*){0,3})($keyword|$keyword_html)((\s?\S*){0,3})/i", $strip, $match, PREG_SET_ORDER));
{
$number=count($match);
if($number > 0)
{
echo "<a href='".$dirlist."/".$label."'>".$label."</a> (".$number.")";
echo "<br />";
}
for ($h=0;$h<$number;$h++)
{
if (!empty($match[$h][3]))
{
printf("<i><b>..</b> %s<b>%s</b>%s <b>..</b></i>", $match[$h][1], $match[$h][3], $match[$h][4]);
}
}
echo "</span><br /><br />";
if($number > 0):
echo "<hr />";
endif;
}
}
}
}
}
}
}
?>
Many thanks In advance
Look up the glob function http://php.net/manual/en/function.glob.php
$found = glob("/path/to/dir/*.pdf");
Edit: Nevermind your question makes it sound completely different to what your code is doing. Im guessing what i posted is incorrect
Simple search, this is not recursive. Give it a directory and it will spit out the found files
$files = glob("c:/xampp/htdocs/*.php");
if(empty($files)) {
echo "No PHP Files Found";
}
else {
foreach($files as $f) {
echo "PHP File Found: ".$f."\n";
}
}
Related
I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.
I have a php search code that returns the results in the page. What I wanna do is limit the number of results per page to 10, and echo a link for more results.
My code is:
$dir = 'www/posts';
$exclude = array('.','..','.htaccess');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
if (!empty($q)) {
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtolower($file),$q)!== false &&!in_array($file,$exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/'.$file;
if (file_exists($fpath)) {
echo "<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date ("d F Y ", filemtime($fpath)) ;
echo "<br>";
}
}
}
closedir($res);
}
else {
echo "";
}
I tried the $q->limit(10); but it doesnt work. Please help me write a working code.
<?php
$dir = 'www/posts';
$exclude = array(
'.',
'..',
'.htaccess'
);
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
$results=[];
if (! empty($q)) {
$res = opendir($dir);
while (false !== ($file = readdir($res))) {
if (strpos(strtolower($file), $q) !== false && ! in_array($file, $exclude)) {
$last_dot_index = strrpos($file, ".");
$withoutExt = substr($file, 0, $last_dot_index);
$fpath = 'posts/' . $file;
if (file_exists($fpath)) {
$results[]="<a href='/search.php?post=$withoutExt'>$withoutExt</a>" . " on " . date("d F Y ", filemtime($fpath));
}
}
}
closedir($res);
}
foreach ($results as $result) {
echo $result;
echo "<br>";
}
if (count($results) > 10 ) {
echo 'results is more than 10, but only 10 results is shown';
}
Here is a completely untested suggestion... I am happy to have a bit of back and forth to iron it out.
if(!empty($_GET['q'])){
// perform some logical validation/sanitization on `$_GET['q']` for stability/security
$path = '../posts'; // this relative path may need some adjusting
$files=glob("$path/*.txt"); // collect all .txt files from the directory
var_export($files);
$filtered=preg_grep('~.*'.preg_quote($q,'/').'.*\.txt$~i',$files); // case-insensitive filename search
var_export($filtered);
if(!empty($filtered)){
$batches=array_chunk($filtered,10); // store in groups of 10
var_export($batches); // check the data
if(!isset($_GET['page'],$batches[--$page])){ // a page has been submitted and that page exists in the batches array (subtract one to sync the page with the index)
$page=0;
}
$leftovers=array_keys(array_diff_key($batches,[$page=>'']));
foreach($batches[$page] as $filename){
$withoutExt=substr($filename,0,strrpos($filename,"."));
$fpath="posts/$filename";
echo "<div><a href='/search.php?post=$withoutExt'>$withoutExt</a> on ",date("d F Y",filemtime($fpath)),"</div>";
}
// here you can list the other pages available from this search
if($leftovers){
echo "Additional pages:";
foreach($leftovers as $offset){
echo " <a href='/search.php?q={$_GET['q']}&page=",++$offset,"'>$offset</a>";
}
}
}
}else {
echo "No Search Terms found";
}
I'm writing a script for download from FTP..
In the form I need to show files and folders..
With ftp_nlist, they come all togethers but I want to know who's who ..
I can't find an easy way to do this:
$contents = ftp_nlist($connection, $rep);
$dossiers =array();
$fichiers = array();
foreach($contents as $content){
//if folder
if (is_folder($content)) $dossiers[] = $content;
//si file
if(is_filex($content)) $fichiers[] = $content;
}
Of course is_file and is_dir don't work with distant files...
I've find something with ftp_rawlist and the size of each result..
like this:
if($result['size']== 0){ //is dir }
But in case of an empty file???
So what id the way to know what is a folder and what is a file??
Thanks!
I've had the same problem and this was my solution:
$conn = ftp_connect('my_ftp_host');
ftp_login($conn, 'my_user', 'my_password');
$path = '/';
// Get lists
$nlist = ftp_nlist($conn, $path);
$rawlist = ftp_rawlist($conn, $path);
$ftp_dirs = array();
for ($i = 0; $i < count($nlist) - 1; $i++)
{
if($rawlist[$i][0] == 'd')
{
$ftp_dirs[] = $nlist[$i];
}
}
I know the above code could be optimised and do just one FTP request instead of two but for my purposes this did the work.
For anyone looking for a cleaner solution, I've found a script to parse ftp_rawlist in this LINK:
Function
function parse_ftp_rawlist($List, $Win = FALSE)
{
$Output = array();
$i = 0;
if ($Win) {
foreach ($List as $Current) {
ereg('([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)', $Current, $Split);
if (is_array($Split)) {
if ($Split[3] < 70) {
$Split[3] += 2000;
}
else {
$Split[3] += 1900;
}
$Output[$i]['isdir'] = ($Split[7] == '');
$Output[$i]['size'] = $Split[7];
$Output[$i]['month'] = $Split[1];
$Output[$i]['day'] = $Split[2];
$Output[$i]['time/year'] = $Split[3];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : false;
}
else {
foreach ($List as $Current) {
$Split = preg_split('[ ]', $Current, 9, PREG_SPLIT_NO_EMPTY);
if ($Split[0] != 'total') {
$Output[$i]['isdir'] = ($Split[0] {0} === 'd');
$Output[$i]['perms'] = $Split[0];
$Output[$i]['number'] = $Split[1];
$Output[$i]['owner'] = $Split[2];
$Output[$i]['group'] = $Split[3];
$Output[$i]['size'] = $Split[4];
$Output[$i]['month'] = $Split[5];
$Output[$i]['day'] = $Split[6];
$Output[$i]['time/year'] = $Split[7];
$Output[$i]['name'] = $Split[8];
$i++;
}
}
return !empty($Output) ? $Output : FALSE;
}
}
Usage
// connect to ftp server
$res_ftp_stream = ftp_connect('my_server_ip');
// login with username/password
$login_result = ftp_login($res_ftp_stream, 'my_user_name', 'my_password');
// get the file list for curent directory
$buff = ftp_rawlist($res_ftp_stream, '/');
// parse ftp_rawlist output
$result = parse_ftp_rawlist($buff, false);
// dump result
var_dump($result);
// close ftp connection
ftp_close($res_ftp_stream);
I've looked at similar posts here but couldn't crack a solution. I'm getting the Strict Standards: Only variables should be passed by reference error here on the strtolower($file['name']))), line. Tried hours now looking for a solution but couldn't figure out how to correct. Can you highlight where I've gone wrong?
Note: Code Edited as per #Kolink's suggestion below:
<?php
require_once 'upload_config.php';
$mydirectory = myUploadDir();
$uploaded_file_counter = 0;
$UploadLimit = $_POST['counter'];
for ($i = 0; $i <= $UploadLimit; $i++) {
$file_tag = 'filename' . $i;
$filename = $_FILES[$file_tag]['name'];
if ($filename != null) {
$rand = time();
$str = "$rand$filename";
// set folder name in here.
$filedir = myUploadDir();
//change the string format.
$string = $filedir . $str;
$patterns[0] = "/ /";
$patterns[1] = "/ /";
$patterns[1] = "/ /";
$replacements[1] = "_";
$dirname = strtolower(preg_replace($patterns, $replacements, $string));
//end of changing string format
//checking the permitted file types
if ($check_file_extentions) {
$allowedExtensions = allowedfiles();
foreach ($_FILES as $file) {
if ($file['tmp_name'] > '') {
/*if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) */
if (!in_array(array_reverse(explode(".", strtolower($file['name'])))[0], $allowedExtensions)) {
$fileUploadPermission = 0;
} else {
$fileUploadPermission = 1;
}
}
}
} else {
$fileUploadPermission = 1;
}
//end of checking the permitted file types
if ($fileUploadPermission) {
if (move_uploaded_file($_FILES[$file_tag]['tmp_name'], $dirname)) {
echo "<p>"; ?>
<div><?php echo "<img style='height:100px;width:200px' src='$dirname'>"; ?></div> <?php
echo "</p>";
$uploaded_file_counter += 1;
}
}
}
}
if ($uploaded_file_counter == 0) {
echo "<br /> <b style='font-weight:bold;color:red'>Opss! Please select an image file<b>";
} else {
echo "<br /> <b>You request " . $i . " image files to upload and " . $uploaded_file_counter . " files uploaded sucessfully</b>";
}
?>
end takes its argument by reference, since it modifies the original array by moving its internal pointer.
Since you appear to be using PHP 5.4, you can do this instead to get the last one:
if( !in_array(array_reverse(explode(".",strtolower($file['name'])))[0],$allowedExtensions))
That said, it's probably better to do it in several steps for readability:
$parts = explode(".",strtolower($file['name']));
$extension = $parts[count($parts)-1];
if( !in_array($extension,$allowedExtensions)) {
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;
}
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