Page 1 of 1

Beginner: Separating a string into words

Posted: Tue Sep 22, 2009 8:08 am
by tabutcher
Basically I have a text file in a similar format like below:

Country Name Age
-----------------------------------------
Italy Joe Hill 39
China Xiao Lin 27


What I'd like to do is to be able to read a line and write it to another text file with an added marker after each field so I could use the explode function.
The new text file would need to look like the following:

Country Name Age
-----------------------------------------
Italy= Joe Hill= 39
China= Xiao Lin= 27


thanks in advance

Re: Beginner: Separating a string into words

Posted: Tue Sep 22, 2009 9:36 am
by Eric!
You can try my old-school C method with tokens then rebuild with your = requirement. But I would skip that and the explode() and just build a keyed array with the tokens.

Code: Select all

$input="Make me into a list of words one at a time.";
$token = strtok($input," "); //find first word before space
while($token)
{
  echo $token . "<br />";
  $token = strtok(" ");//get the next word until end of string
}
Someone with regex skills could do a quicker search and replace with s/ /g but I have no game there.

Re: Beginner: Separating a string into words

Posted: Tue Sep 22, 2009 10:56 am
by Mark Baker
str_word_count() with a format mode of 1 or 2

Re: Beginner: Separating a string into words

Posted: Thu Sep 24, 2009 11:47 pm
by tabutcher
@Eric!
I implemented the strtok() into my code but found that i needed the split to be made after the name of the country and name.
At the moment the script is splitting the string at every ' '(space).

Re: Beginner: Separating a string into words

Posted: Fri Sep 25, 2009 10:24 pm
by Eric!
Yeah, I didn't do all the work for you. I just showed you the technique. You'll have to write some code to rebuild it for explode() or to put it into an array.

But here's some more code to help you. I don't know for sure if it will work but it is a starting point.

Code: Select all

$input="Make me into a list of words one at a time.";
$token = strtok($input," "); //find first word before space
$data=array();
while($token)
{
  $key=$token;
  $token=strtok(" ");//get the next word until end of string
  $value=$token;
  $data[$key]=$value;
}
// to access all the values
foreach($data as $name => $amount)
{
    echo "KEY: $name, VALUE: $amount <br />";
}