Hey, I would like to know how to open a txt file and search it using PHP and record every string between the following 2 strings: 1. ><a href="/cool/of/ 2. /"><img src="/awesome.gif" Then create a new txt file with each string found on a new line
Well inbetween those 2 strings are usernames, i need to list them all from the file by removing them from the source
$searchIn = file_get_contents('somefile.txt'); preg_match_all('@><a href="/cool/of/(.*?)/"><img src="/awesome\.gif"@',$searchIn,$matches,PREG_SET_ORDER); $userNames = $matches[0]; unset($matches); $saveAs = implode("\n\r",$userNames); file_put_contents('usernames.txt',$saveAs); PHP: Untested but along those lines.
if(!function_exists("file_put_contents")) { function file_put_contents( $file, $data ) { $handle = fopen( $file, "w+" ); $write = fwrite( $handle, $data ); fclose( $handle ); return $write ; } }
<?php function put_strings( $infile, $outfile ) { if(!($search = file_get_contents( $infile ))): print("Cannot retrieve $infile<Br/>\n"); return false; endif; preg_match_all( '#<a href="/cool/of/(.*?[^/])/">#si', $search, $found ); if( $found ): $handle = fopen( $outfile, "w+" ); if( !$handle ): print( "Cannot open $outfile for writing<br/>\n" ); return false; endif; $write = fwrite( $handle, implode("\r\n", $found[1] ) ); fclose( $handle ); endif; return !$write ? false : count( $found[1] ) ; } if( !put_strings( 'test.php', 'out.txt' ) ): echo "CAN'T<br/>\n"; else: echo "DONE<br/>\n"; endif; ?> PHP: