Page 1 of 1
How to check each line of a file?
Posted: Mon Mar 13, 2006 1:06 pm
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?
Posted: Mon Mar 13, 2006 1:13 pm
by hawleyjr
Posted: Mon Mar 13, 2006 1:31 pm
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?
Posted: Mon Mar 13, 2006 1:33 pm
by hawleyjr
From the first link:
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.
Posted: Mon Mar 13, 2006 2:00 pm
by djwk
I don't understand where I enter the string of text to search each line for
Posted: Mon Mar 13, 2006 2:13 pm
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.
Posted: Mon Mar 13, 2006 2:37 pm
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 />';
}
}