Iterate the lines in a text file - php

I want to read the text file line by line using php while copying only these values 1.23 , 0.5 , -1.8903, 186 , -0095
I will use strtok() to extract the part of each line I want.
I need help writing the code to iterate through each line.

While you read the file you can explode the file into an array of lines, then split by space and get the first element, like :
$text = "00123123 asdjasdjjdaswd
-32423 asdasda sdsagfgasdf
42 adklsdfkasdfsdf";
$lines = explode(PHP_EOL, $text); # EOL = End of line
foreach($lines as $line){
$array = explode(" ", $line);
echo $value = $array[0];
echo "\n";
}
/* Outputs:
00123123
-32423
42
*/
Alternatively you could write a regex that will get you the contents before the first whitespace per line.

I have used given code:-
$file="test.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
$line = fgets($handle);
$array = explode(" ", $line);
echo $value = $array[0];
echo "\n";
$linecount++;
}
fclose($handle);

Related

Replace character of a particular line with incremental number per line [duplicate]

This question already has answers here:
Replace substrings with an incremented counter value
(5 answers)
Closed 2 years ago.
I have a text file (data.txt) with the following lines
# one
# two
a-two
b-two
c-two
# three
a-three
b-three
# four
I would like to replace # with incremental number per line so to be like this
1 one
2 two
a-two
b-two
c-two
3 three
a-three
b-three
4 four
I have try to do this
<?php
$path_to_file = 'data.txt';
$what_to_replace = '#';
$i = 0; // initial count
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace($what_to_replace, $i++,$file_contents);
file_put_contents($path_to_file,$file_contents);
?>
it did changed in all lines with # but not incrementally
Here's a simple way via preg_replace_callback():
$i = 1;
$file_contents = preg_replace_callback('/^#/m', function($match) use (&$i) {
return $i++;
}, $file_contents);
The m (multiline) flag is important - it will force our pattern to match # at the start of any line, not just the first.
I think you have to iterate over all the lines and replace the hash one by one. Of course, you can use some preg_replace as well to only replace the # at the line beginning: https://www.php.net/manual/en/function.preg-replace.php
$result = '';
$handle = fopen("data.txt", "r");
$i = 1;
if ($handle) {
while (($line = fgets($handle)) !== false) {
$content .= str_replace('#', $i++,$line) . "\n";
}
fclose($handle);
} else {
// error opening the file.
}
file_put_contents('data.txt', $result);
$path_to_file = 'data.txt';
$what_to_replace = '#';
$i = 1; // initial count
$file_contents = file_get_contents($path_to_file);
$lines = explode(PHP_EOL, $file_contents);
$new_lines = [];
foreach ($lines as $line) {
if (strpos($line, '#') !== false) {
$new_lines[] = str_replace('#', $i, $line);
$i++;
} else {
$new_lines[] = $line;
}
}
file_put_contents($path_to_file, implode(PHP_EOL, $new_lines));
We can split the text line-by-line, then process each line individually, looking for a # at the start of the line & modifying the output in those cases.
The preg_replace_callback approach is better than this one, IMO.
$text = file_get_contents(...);
$lines = explode("\n", $text); // split by unix-style line break
$out = []; // For storing the modified lines
$i=0;
foreach ($lines as $line){
if (substr($line,0,1)=='#'){
//replace the first character & increment the counter if line starts with #
$i++;
$line = $i.substr($line,1);
}
//append the SOMETIMES modified line to the output
$out[] = $line;
}
// convert array of lines to string
$fixedText = implode("\n", $out);
See https://stackoverflow.com/a/28725803/802469 for a more robust version of the explode("\n", $text) line.
Personally, I like the $out = []; ...; implode(...) approach. I find it easier to work with & to visualize in my mind. Using an $out = ""; $out .= $line."\n"; approach would work just as well. I suspect any performance increase from going with string would be negligible, but might lower your carbon footprint a small amount.
If you have serious performance/resource concerns (extremely large files) then the fopen()/while fgets() approach would be better, and fopen/fwrite() could be used to append each output line to a file without using up memory for an output string.

Finding all lines in text file beginning with a character then a space in php

I have a text file and in it i want to only read the lines that start with an r then a space.
I have tried strpos but it does not seem to work.
$r="r ";
$file = file_get_contents('cached-consensus', true);
$n = explode("\n", $file);
foreach($n as $line){
$pos= strpos($line,$r);
echo $pos;}
Use this:
$file = file_get_contents('cached-consensus', true);
$n = explode("\n", $file);
foreach($n as $line){
if(0 === strpos($line, "r ")){
// do whatever you want with the line
}
}
This checks that $line starts with 'r '. Currently you're just echoing the position of the string (this should be 0).

Count specific lines in text file

How to count specific lines in a text file depending on a particular variable in that line.
For example i need to count the lines of a text file only containing for instance $item1 or $item2 etc.
Sounds like you need something like what grep -c do in the shell, try something like this:
$item1 = 'match me';
$item2 = 'match me too';
// Thanks to #Baba for the suggestion:
$match_count = count(
preg_grep(
'/'.preg_quote($item1).'|'.preg_quote($item2).'/i',
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
)
);
// does the same without creating a second array with the matches
$match_count = array_reduce(
file('somefile_input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES),
function($match_count, $line) use ($item1, $item2) {
return
preg_match('/'.preg_quote($item1).'|'.preg_quote($item2).'/i', $line) ?
$match_count + 1 : $match_count;
}
);
The above code sample uses the file() function to read the file into an array (splitted by lines), array_reduce() to iterate that array and preg_match() inside the iteration to see if a line matched (the /i at the end makes it case-insensitive).
You could use a foreach as well too.
This code reads file.php and counts only lines containing '$item1' or '$item2'. The check itself could be finetuned, since you have to add a new stristr() for every word you want to check.
<?php
$file = 'file.php';
$fp = fopen($file, 'r');
$size = filesize($file);
$content = fread($fp, $size);
$lines = preg_split('/\n/', $content);
$count = 0;
foreach($lines as $line) {
if(stristr($line, '$item1') || stristr($line, '$item2')) {
$count++;
}
}
echo $count;
Read your file line by line and use strpos to determine if a line contains a specific string/item.
$handle = fopen ("filename", "r");
$counter = 0;
while (!feof($handle))
{
$line = fgets($handle);
// or $item2, $item3, etc.
$pos = strpos($line, $item);
if ($pos !== false)
{
$counter++
}
}
fclose ($handle);

How do i hide some words in a string from a txt in php

I'm new to php and have the following code to show the string there's inside a .txt file in my web:
<?php
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;
}
?>
I'd like to know how to select some words to be hidden. In my case I want to hide the numbers (01,02,03,04,05,1,2,3,4,5) in the line.
I also want to replace the whole line for another one in case it starts with a certain word. For example if the line starts with the word "example" replace the whole line and only display the words "hello world"
To remove the numbers:
$str = preg_replace("/\d/", "", "This 1 is 01 2 a 2 test 4 45 aaa");
echo $str;
Output:
This is a test aaa
Link to fiddler
To replace the the whole line (only if it starts with "example") with "hello world":
$str = "example This 1 is 01 2 a 2 test 4 45 aaa";
echo preg_replace("/^example.*/", "hello world", $str);
Output:
hello world
Link to fiddler
Combining both together will give us:
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
$line = preg_replace("/^example.*/", "hello world", $line);
$line = preg_replace("/\d/", "", $line);
print $line;
}
<?php
$hideStartWith = "example";
$replaceWith = "hello world";
$hideText = array("01","02","03","04","05","1","2","3","4","5");
$file = "file.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
if(substr($line, 0, strlen($hideStartWith)) === $hideStartWith){
$line = $replaceWith; //print "hello world" if the line starts with "example"
} else {
foreach($hideText as $h)
$line = str_replace($h, "", $line); //filtering the numbers
}
print $line;
}
?>
hope this helps.
for the entire line replace, try:
if (stripos($my_line, "example")===0){
$my_line = "example";
}
http://php.net/manual/en/function.str-replace.php

PHP modify TXT file

I have a ID.txt file that looks like this:
"http://something.net/something-ak/41389_718783565_1214898307_q.jpg"
"http://something.net/something-ak/372142_106502518141813_1189943482_q.jpg"
and so on
I want to use PHP to open the file and remove everything before the first " _ " and everything after the second " _ " so I wind up with this:
718783565
106502518141813
and so on
Thing is I don't really know how to do that.
This is what I have so far:
<?PHP
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode('\n', $line_of_text);
// Remove everything before the first "_" and everything after the last "_".
// echo the line
}
fclose($file_handle);
?>
Can someone help me fille in the blanks?
This is what I would do, although a regex might be shorter or more efficient:
$file_handle = fopen("ID.txt", "rb");
while (!feof($file_handle) )
{
$line_of_text = fgets($file_handle);
$parts = explode("\n", $line_of_text);
foreach ($parts as $str)
{
$str_parts = explode('_', $str); // Split string by _ into an array
array_shift($str_parts); // Remove first element
echo current($str_parts)."\n"; // echo current element and newline
// Same as $str_parts[0]
}
}
fclose($file_handle);
Demo: http://codepad.org/uFbVDtbR
Not a big deal, but $lines might be a better variable name there instead of $parts.
If you do need to write this back to the file, you can do this:
ob_start();
// code used above
$new_content = ob_get_clean();
file_put_contents("ID.txt", $new_content);
Relevant references:
http://php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.array-shift.php
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.file-put-contents.php
Just use file in a loop
$content = "";
foreach(file("ID.txt", FILE_SKIP_EMPTY_LINES) as $line){
$parts = explode('_', $line);
$content .= $parts[1] . "\n";
}
file_put_contents("ID.txt", $content);
If you want to achieve this by awk,
awk -F _ '{print $2}' ID.txt
Try this
preg_match('/(.*?)(.+?)(.*)/',$line,$matches);
$matches[2] will give the required string
This should work
<?php
// open files
$file_handle = fopen("ID.txt", "rb");
$new_file_handle = fopen("ID2.txt", "wb");
while (!feof($file_handle) ) {
$str = fgets($file_handle);
$start = strpos($str, '_'); // find first "_"
$end = strpos($str, '_', $start + 1); // find next "_"
$newstr = substr($str, $start + 1, $end - $start - 1) . "\n";
fputs($new_file_handle, $newstr);
}
// close files
fclose($file_handle);
fclose($new_file_handle);
// rename
rename("ID2.txt", "ID.txt");
$TXT = file_get_contents(__DIR__.'/in.txt');
$NewTXT = preg_replace('~^.+/[0-9]+_([0-9]+)_.+?$~mi', '$1', $TXT);
file_put_contents(__DIR__.'/out.txt', $NewTXT);
Just rename the .txt files accordingly.

Categories