I'm reading a text file of email addresses and outputting the domain only (with the # symbol). I need to alphabetize the list and then output to display on screen
Here is my code thus far:
<?php
$file_handle = fopen("file.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$parts = explode("#", $line);
$Id = $parts[count($parts) - 1];
echo "#" . $Id . "<br>";
}
fclose($file_handle);
?>
How can I initiate a sort to alphabetize the list?
This should work for you:
(Here I just get every line of the file with file(). Then I go through each line with array_map() where I only return the domain into the array $lines. At the end I sort the array with sort() and print it)
<?php
$lines = array_map(function($v){
return "#" . explode("#", $v)[1];
}, file("test.txt"));
sort($lines);
foreach($lines as $line)
echo $line . "<br />";
?>
Example input/output:
a.b#x.com
a.c#a.de
e.s#b.cu
#a.de
#b.cu
#x.com
Related
Let's say I have this in my text file:
Author:MJMZ
Author URL:http://abc.co
Version: 1.0
How can I get the string "MJMZ" if I look for the string "Author"?
I already tried the solution from another question (Php get value from text file) but with no success.
The problem may be because of the strpos function. In my case, the word "Author" got two. So the strpos function can't solve my problem.
Split each line at the : using explode, then check if the prefix matches what you're searching for:
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
list($prefix, $data) = explode(':', $line);
if (trim($prefix) == "Author") {
echo $data;
break;
}
}
Try the following:
$file_contents = file_get_contents('myfilename.ext');
preg_match('/^Author\s*\:\s*([^\r\n]+)/', $file_contents, $matches);
$code = isset($matches[1]) && !empty($matches[1]) ? $matches[1] : 'no-code-found';
echo $code;
Now the $matches variable should contains the MJMZ.
The above, will search for the first instance of the Author:CODE_HERE in your file, and will place the CODE_HERE in the $matches variable.
More specific, the regex. will search for a string that starts with the word Author followed with an optional space \s*, followed by a semicolon character \:, followed by an optional space \s*, followed by one or more characters that it is not a new line [^\r\n]+.
If your file will have dinamically added items, then you can sort it into array.
$content = file_get_contents("myfile.txt");
$line = explode("\n", $content);
$item = new Array();
foreach($line as $l){
$var = explode(":", $l);
$value = "";
for($i=1; $i<sizeof($var); $i++){
$value .= $var[$i];
}
$item[$var[0]] = $value;
}
// Now you can access every single item with his name:
print $item["Author"];
The for loop inside the foreach loop is needed, so you can have multiple ":" in your list. The program will separate name from value at the first ":"
First take lines from file, convert to array then call them by their keys.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$pieces = explode(":", $line);
$array[$pieces[0]] = $pieces[1];
}
} else {
// error opening the file.
}
fclose($handle);
echo $array['Author'];
I have created the code below and it all works completely fine my problem is that is will add as it goes along and display everything whereas i just need the last array element i have tried array_pop and the end function to no avail any ides?
$Count = 0;
$file_handle = fopen("test2.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$arr = array($parts[8]);
for($i=0;$i<count($arr);){
$count = $count + $arr[$i]/1024;
$results= array($count);
}
echo '<p>';
print_r($results);
echo '</p>';
}
fclose($file_handle);
Try using end()
echo '<p>';
end($results);
echo '</p>';
Assuming your array is numeric, couldn't you simply only display the last element like this:
$lastRec=count($results);
print_r($results[$lastRec]);
$file=fopen("question.txt","r");
while(!feof($file))
{
echo "<h3>". fgets($file)."</h3>"."<br />";
for($i=0;$i<=3;$i++)
{
echo fgets($file)."<br />";
}
}
$lines =file("filename.txt");
and then $lines[4] will return you fifth line.
Find and replace the line. Look at str_replace function at http://php.net/manual/en/function.str-replace.php :)
Maybe a better option in this case... Use the file($path) function to get the lines into an array, then loop through it.
$lines = file($path, FILE_IGNORE_NEW_LINES);
$remove = "balblalbllablab";
foreach($lines as $key => $line)
if(stristr($line, $remove)) unset($lines[$key]);
$data = implode('\n', array_values($lines));
$file = fopen($path);
fwrite($file, $data);
fclose($file);
how to get only the specific content from a file using PHP.
I have a file with content:
reference 1.pdb
mobile 4r_1.pdb
ignore
fit
mobile 4r_10.pdb
ignore
fit
mobile 4r_22220.pdb
ignore
fit
Now, I want to take all the names i.e. (output)
4r_1
4r_10
4r_22220
in an array and print it.
The program i have written in php doesn't work properly, can have a look
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
if ($output4 !="/mobile/i")
{
print $output4;
print "\n";
}
Please help! to extract only the names
Try this:
$convert = explode("\n", $data); // take it in an array
$filenames = array();
foreach ($convert as $item) {
if(strstr($item,'mobile')) {
array_push($filenames,preg_replace('/mobile[\s]?([A-Za-z0-9_]*).pdb/','${1}',$item));
}
}
Now all the file names (assuming they are file names) are in the array $filenames
preg_grep returns an array of matching lines, your condition is treating $output4 as a string.
Loop over the array to print out each line and use either substr or str_replace to remove the unwanted characters from the string
$data = file_get_contents('test.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
foreach($output4 as $entry) {
print str_replace("mobile ", "", $entry) . "\n";
}
Below code should work:
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert);
if (count($output4))
{
foreach ($output as $line) {
print $line; // or substr($line, 6) to remove mobile from output
print "\n";
}
}
Note:
Instead of doing
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
You may read a file into array with file() function:
$convert = file('file.txt'); // to read the file
Try this:
$content = file_get_contents('file.txt');
$lines = explode("\n", $content);
foreach ($lines as $line) {
if (preg_match('/^mobile\s+(.+)$/', $line, $match)) {
echo $match[1], "\n";
}
}
Hy everyone, I'm having trouble with properly nesting while loops to read from 2 arrays.
I have 2 files from which I read the content:
file1: item_list.txt
string1 \n
string2 \n
string3 \n
...
file2: item+info.txt
string3 \t info1 \t info2 \t info3
string1 \t info7 \t info1 \t info4
string5 \t info2 \t info3
string2 \t info2 \t info4 \t info1
(values are separated by new lines and tabs only, I added one space between characters here just to increase readability).
I read from files using fgetcsv() function, and each row from file is stored as an array into a variable $data. I created a while loop with condition (!feof($fp)) to read through the file until the last row. But I can't quite properly nest the second loop.
What I want to do with this:
read the first string found in file1, go to file2 and try to find that string. If there's a match, get the info data for that string (all of the data, or just one, doesn't matter). If there's no match, return message "no match". In either case, once the second loop has done it's thing, I need to read the second string in file1, and do the search in file2 again. Repeat this as long as there is something to read from the file1.
here are two versions of my code, they don't work, and I can't figure out why.
//opening the files
$fp = fopen("$DOCUMENT_ROOT/test/item_list.txt", "r"); #raw item list
$pf = fopen("$DOCUMENT_ROOT/test/item+info.txt", "r"); #item+info list
//read from first file
$line=0;
while (!feof($fp)){
$line++;
$data1 = fgetcsv($fp, "1000", "\n");
$item1= $data1[0];
echo "line: $line. item_list: ".$item1; //just to see on screen what's happening
print_r($data1); //same here, just to see what's going on
echo"<br />";
//searching for string in file2
$row=0;
while (!feof($pf)){
$row++;
$data2 = fgetcsv($pf, "1000", "\t");
$item2= $data2[0];
echo "line: $row. item+info: ".$item2; //just checking things on screen
print_r($data2); //here too
echo "<br />";
//conditioning
//equal strings
if ($string1== $string2)
echo $data2[1]."<br />";
break;
}
}
fclose($fp);
fclose($pf);
this used to work as long as the items in item_list.txt and item+info.txt are oredered
exactly the same (string1\nstring2\string3 ->
string1\tinfo1\nstring2\tinfo2\nstring3\tinfo3 - but that's never going to happen in my
case, it's impossible to order the items like that)
I tried to do it with foreach() statement do itterate through arrays, but the result is something that I can't make any sense out of.
while (!feof($fp)){
$data1 = fgetcsv($fp);
foreach ($data1 as $token1) {
while (!feof($pf)) {
$data2 = fgetcsv($pf);
foreach ($data2 as $value) {
explode ("\t", $value);
if ($token1 == $value[0])
echo $value[1];
}
break;
}
}
}
This should do it:
$file1 = file($DOCUMENT_ROOT . '/test/item_list.txt');
$file2 = file($DOCUMENT_ROOT . '/test/item+info.txt');
foreach ($file1 as $line)
{
$line = rtrim($line); // just in case ...
if ($line === '') continue;
foreach($file2 as $infoline)
{
$infoline = explode("\t", rtrim($infoline);
if ($line === $infoline[0])
{
array_shift($infoline);
echo $line . '<br /><br />' . implode('<br />', $infoline);
// $results[$line] = $infoline; // uncomment this if you need the search results stored for later use
break;
}
}
}
Here's a rough shot at it:
$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';
# Init the Raw Array
$content2raw = array();
# Get the File Contents for File 2
$file2 = file_get_contents( $filename2 );
# Split it into an Array by Line Breaks
$content2raw = preg_split( "/\n/" , $file2 , -1 , PREG_SPLIT_NO_EMPTY );
# Unset the variable holding the file contents
unset( $file2 );
# Init the Fixed Array
$content2 = array();
# Loop through the Raw Array
foreach( $content2raw as $l ){
// Each Line of Filename2
# Split the Line on Tabs
$t = preg_split( "/\s*\t\s*/" , $l , -1 );
# Set the Fixed Array, using the first element from the line as the key
$content2[ $t[0] ] = $t;
}
# Unset the Raw Array
unset( $content2raw );
# Get the File Contents from File 1
$file1 = file_get_contents( $filename1 );
# Split it into an Array by Line Breaks
$contents1 = preg_split( "/\n/" , $file1 , -1 , PREG_SPLIT_NO_EMPTY );
# Unset the variable holding the file contents
unset( $file1 );
# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
# Check whether a matching element exists in the array from File 2
if( !array_key_exists( $k , $content2 ) ){
// No Match Found
echo 'No Match';
}else{
// Match Found
echo 'Match Found';
var_dump( $content2[$v] );
}
}
Amendment, as per comment/feedback from #Bluewind
$filename1 = 'item_list.txt';
$filename2 = 'item+info.txt';
# Open and Split the file into an Array by Line
$content2raw = file( $filename2 );
# Init the Fixed Array
$content2 = array();
# Loop through the Raw Array
foreach( $content2raw as $l ){
// Each Line of Filename2
# Split the Line on Tabs
$t = preg_split( "/\s*\t\s*/" , $l , -1 );
# Set the Fixed Array, using the first element from the line as the key
$content2[ $t[0] ] = $t;
}
# Unset the Raw Array
unset( $content2raw );
# Open and Split the file into an Array by Line
$contents1 = file( $filename1 );
# Loop through the Lines, using each line as the Key to look for
foreach( $content1 as $v ){
# Check whether a matching element exists in the array from File 2
if( !array_key_exists( $k , $content2 ) ){
// No Match Found
echo 'No Match';
}else{
// Match Found
echo 'Match Found';
var_dump( $content2[$v] );
}
}
This is actually much less code than you seem to think. First, you read an info file and build a hash table out of it:
foreach(file("info_list") as $line) {
$line = explode("\t", trim($line));
$info[$line[0]] = $line;
}
then you iterate through the items file and look if there are matching entries in the hash:
foreach(file("item_list") as $line) {
$item = trim($line);
if(isset($info[$item]))
// we have some info for this item
else
// we have no info for this item
}
that's basically all about this