Click to See Complete Forum and Search --> : NEWBIE: Check for lines in textfile...


mf22cs
05-29-2003, 07:06 AM
Hi,

I would like to know if there is a way of checking if a string is found in a textfile.

Exemple:
--- file.txt ---
oldtest@domain.com
newtest@domain.com
best@domain.com
--- end ---

Then i want to know if a specific line is found in that file... exemple:
best@domain.com shall return true
test@domain.com shall return false

-----------------------
Later on the action is to include/exclude lines in that file. But include shall only work IF the test is false, and vice versa. But that part is not part of the question... but if someone know how to do that I will not flame him/her for sharing there knowing on that part. :D
-----------------------

Thanx in advance!
/Marcus

pyro
05-29-2003, 07:31 AM
Try something like this out:

<html>
<head>
<title>Search File</title>
<style type="text/css">
a {
color:darkblue;
}
</style>
</head>
<body>

<form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="email">
<input type="submit" name="submit" value="Check links">
</form>

<?php

$file = "http://www.yourdomain.com/dir/file.txt"; # direct path to your file
$search = $_POST['email'];
$x = 0;

if ($_POST['submit']) {

#open file, or print message if opening fails
$contents = @file($file) or die ("Failed to open <a href=\"$file\">$file</a>. Please be sure it is an absolute URL.");

foreach ($contents as $line_num => $line) { #loops through each line of the file
if (preg_match("/$search/", $line)) { #does a regexp search for the email
$x = 1;
}
}

if ($x == 1) {
echo "$search was found in the file.";
}
else {
echo "$search was not found in the file.";
}
}

?>

</body>
</html>

mf22cs
06-02-2003, 05:26 AM
I think I should use:


preg_match("/\b$search/\b", $line))


Am I wrong?

/Marcus

mf22cs
06-02-2003, 05:28 AM
Hmmm....

Seems like the forum drops some characters...

/Marcus

pyro
06-02-2003, 06:55 AM
Use [ code ] rather than [ php ] (minus spaces, of course) and I will let you know... Either way, did you try the code I posted?

mf22cs
06-02-2003, 07:05 AM
No, I haved not tried it yet... :o

But thatīs because the rest of the code is not finished yet (hopfully it will be ready today).

But my question arised as I read the "manual" on "preg_match" at http://www.php.net.

This code:

preg_match("/\b$search\b/i", $line)

acording to the manual will not let $search = "name@domain.com" find the line "firstname@domain.com" but it will find the line "NAME@DOMAIN.COM" (if caps-lock error) and "Name@domain.com".

/marcus

pyro
06-02-2003, 08:08 AM
Yep, that was an overlook on my part... And, if all that is supposed to be on the line is the email (ie, no words/spaces/etc before or after) this is how you would do it:

preg_match("/^$search$/i", $line)