[thelist] parsing txt file?
Noah St. Amand
noah at tookish.net
Wed Nov 30 01:58:05 CST 2005
Hi Flavia,
Flavia Tarzwell (FayeC) wrote (11/29/05 6:59 PM):
> But now I have to find a way to add a line like:
> "Welcome to baby "familyname"'s page!"
> The "familyname" is not the same as the username so I had the idea of
> creating a simple txt file with :
> username="familyname"
> And then parsing the "familyname" out of the file.
> I need the outputString to be what is between the "" and not the
> $username....
Here's how I'd do it (watch for line wrap):
<?php
$username = $_POST['username'];
$user_file = "clientlist.txt";
//read the contents of the file into an array (each line is a single
//element in the array)
$user_lines = file($user_file);
//iterate through each element in the array (i.e., each line in the
//original file)
foreach($user_lines as $user_line) {
//separate each line into the username and the family name by
//converting each line into an array with the "=" being the point of
//separation -- the result is an array with two elements, the first
//the part before the "=", the second the part after the "="
$user_line_components = explode('=', $user_line);
//if the first element of the new array matches the username, then the
//second part will contain the family name we need -- we also remove
//the quotes that are in the file, and trim any spaces that might have
//crept in to the file
if ($user_line_components[0] == $username) $family_name =
trim(str_replace('"', '', trim($user_line_components[1])));
}
//now $family_name contains the family name from the file
print("Welcome to baby {$family_name}'s page!");
?>
It may be more efficient to do it with a regular expression, but they
give me nightmares.
Let me know if you have any trouble with this.
Cheers,
Noah
More information about the thelist
mailing list