Beginner: Separating a string into words

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

Post Reply
tabutcher
Forum Newbie
Posts: 20
Joined: Fri Aug 21, 2009 7:10 am

Beginner: Separating a string into words

Post 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
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Beginner: Separating a string into words

Post 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.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Beginner: Separating a string into words

Post by Mark Baker »

str_word_count() with a format mode of 1 or 2
tabutcher
Forum Newbie
Posts: 20
Joined: Fri Aug 21, 2009 7:10 am

Re: Beginner: Separating a string into words

Post 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).
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: Beginner: Separating a string into words

Post 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 />";
}
Post Reply