Page 1 of 1

problem with strings .

Posted: Mon Feb 25, 2008 11:34 am
by loozi
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

Re: problem with strings .

Posted: Mon Feb 25, 2008 11:45 am
by yacahuma

Code: Select all

 
foreach (file('test.dat') as $line)
{
  list($f,$l) = split(' ',$line);
  echo '<br>First name:' . $f .'<br>Last name:' . $l;
}  
 

Re: problem with strings .

Posted: Mon Feb 25, 2008 11:49 am
by loozi
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!

Re: problem with strings .

Posted: Mon Feb 25, 2008 11:56 am
by robble
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);
 ?>