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
loozi
Forum Newbie
Posts: 10 Joined: Sun Feb 24, 2008 4:04 am
Post
by loozi » Mon Feb 25, 2008 11:34 am
hey, I'm trying to create a code that separates 2 strings by the space between them. the code loads a text file line by line -
Code: Select all
<?php
$names = "names.txt";
$fh = fopen($names, 'r');
$lines = file($names);
$count = count($lines);
echo "$count names found\n\r";
for ($i=1; $i<=$count; $i++)
{
$theData = fgets($fh);
echo $data;
}
fclose($fh);
?>
every line contains First name and Last name, examples:
Lynne Bonnett
Wilson Hulsey
I want the output to be like this =
First name: Lynne
Last name: Bonnett
yacahuma
Forum Regular
Posts: 870 Joined: Sun Jul 01, 2007 7:11 am
Post
by yacahuma » Mon Feb 25, 2008 11:45 am
Code: Select all
foreach (file('test.dat') as $line)
{
list($f,$l) = split(' ',$line);
echo '<br>First name:' . $f .'<br>Last name:' . $l;
}
loozi
Forum Newbie
Posts: 10 Joined: Sun Feb 24, 2008 4:04 am
Post
by loozi » Mon Feb 25, 2008 11:49 am
yacahuma wrote: Code: Select all
foreach (file('test.dat') as $line)
{
list($f,$l) = split(' ',$line);
echo '<br>First name:' . $f .'<br>Last name:' . $l;
}
Woah, that was fast, works like a charm. Thanks!
robble
Forum Newbie
Posts: 11 Joined: Fri Aug 24, 2007 6:34 am
Post
by robble » Mon Feb 25, 2008 11:56 am
Just got beaten to it...
You can use a function like explode($delimiter,$stringtosplit) to split a string into an array using $delimiter.
Same as below but more like your code with html line breaks! I've used trim() to get rid of excess whitespace and then chosen to ignore blank lines...
Code: Select all
<?php
$names = "names.txt";
$fh = fopen($names, 'r');
$lines = file($names);
$count = count($lines);
echo "$count lines found<br /><br />";
for ($i=0; $i<=$count; $i++)
{
$theData = fgets($fh);
$trimmedData = trim($theData);
if($trimmedData!="")
{
$names = explode(" ",$theData);
echo "First Name: ".$names[0]."<br />";
echo "Last Name: ".$names[1]."<br /><br />";
}
}
fclose($fh);
?>