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
Beginner: Separating a string into words
Moderator: General Moderators
Re: Beginner: Separating a string into words
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.
Someone with regex skills could do a quicker search and replace with s/ /g but I have no game there.
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
}-
Mark Baker
- Forum Regular
- Posts: 710
- Joined: Thu Oct 30, 2008 6:24 pm
Re: Beginner: Separating a string into words
str_word_count() with a format mode of 1 or 2
Re: Beginner: Separating a string into words
@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).
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
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.
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 />";
}