How to check each line of a file?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
djwk
Forum Commoner
Posts: 56
Joined: Tue Mar 07, 2006 2:14 pm

How to check each line of a file?

Post by djwk »

Hi there,

I want to check each line from a text file for a certain string.

Lets say I wanted to find: Hello

and the file contained:
Hi
Boo
Hello
Hiya
It would, lets say set the variable $found, to 1

and if it couldn't find Hello.. $found = 0

How would I do this?
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

djwk
Forum Commoner
Posts: 56
Joined: Tue Mar 07, 2006 2:14 pm

Post by djwk »

Sorry, I have had a look at that and I am a beginner at PHP.

I'm not sure how to use that code to build the script that I want.


Could anyone give me an example snippet?
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

From the first link: :roll:

Code: Select all

<?php
// Get a file into an array.  In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file('http://www.example.com/');

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
   echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// Another example, let's get a web page into a string.  See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
?>

Replace the 'http://www.example.com/' with what ever file you are trying to open.
djwk
Forum Commoner
Posts: 56
Joined: Tue Mar 07, 2006 2:14 pm

Post by djwk »

I don't understand where I enter the string of text to search each line for
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

The code above will put your file into a PHP array. You will need to loop through the array or use and array function such as array search to to find the text.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

$search = 'some string';

//when using against actual file uncomment this and comment other $file
//$file = file('/path/to/file.txt');

//just to test without file
$file = array('some string', 'blah', 'blah2', 'some string will still match this');

foreach ($file as $ln => $content) {
   if (strpos($content, $search) !== false) {
      echo 'Line #'.$ln.' match. <br />';
   }
}
Post Reply