Jump to content

Takes the whole line and prints if the search sting matches.


new2code

Recommended Posts

Hi! :-*

I need php script that would open a text file, look for a string i specified, and if it finds that string, it will take that entire line in the text file and write it to a file, or atleast print it on screen. I'm new to php.

Any help would be appreciated.

 

for example if i have

A	147431	144303	141872	144785	142446	144562	141555	145865	143143	145916		
B	143684	143123	143514	143658	142608	141691	142373	141876	142263	138982	
C	142396	141927	139827	140461	138406	142819	145473	140561	142327	141502		
A	141651	142869	141524	141891	143055	138903	143952	142527	139659	141755		
E	141000	143583	142330	140254	139120	139912	138813	139317	140466	140644	
A	143092	138276	141201	145585	144741	140144	142902	138926	145236	140625		
G	143110	141567	144070	145861	140292	138486	151661	138287	137014	140431		
H	139878	140626	142356	141335	140446	137627	141406	140058	139457	138107	

 

I want all the lines starting with A(tab) to be written to another file or print it on screen.

 

I know this code below does smiler thing but it deletes the whole line if it has an "A" but I need something which will look for  A (tab space) beginning of a line and copy the whole line to a file.

 

<?php

$key = "A"; //looks for A

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
      if (!strstr($line,$key)) //look for $key in each line
            fputs($f,$line); //place $line back in file
}
fclose($f);

?>

 

Thank you so much for all in advance, this forum is great.

 

try the following

 

<?php

$key = "A"; //looks for A

//load file into $fc array

$fc=file("some.txt");

//open same file and use "w" to clear file

$f=fopen("some.txt","w");

//loop through array using foreach

foreach($fc as $line)
{
      if (preg_match("/$key/",$line)){ //look for $key in each line
            fwrite($f,$line); //place $line back in file
}
}
fclose($f);

?>

 

Stuie

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.