Splitting a string line by line

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
Jim
Forum Contributor
Posts: 238
Joined: Fri Apr 19, 2002 5:26 am
Location: Near Austin, Texas

Splitting a string line by line

Post by Jim »

Using explode, I'd like to split something like the following:

Code: Select all

This|is|a|line
This|is|a|line2|
Where each line is separated in to elements [0] , [1] , [2] and [3].
The question I have is how to reset the pointer at the beginning of each new line to ensure I don't have [0] [1] [2] [3] [4] [5] [6]... etc.

What thinkest thou?
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

You mean so you end up with a multidimension array, where [0][2] is the third word of line 1, and [1][1] is the second word of line 2 etc ?
If so then something like the following should do it.

Code: Select all

<?php
$lines = file('line.txt'); //file containing the text lines
foreach($lines as $key=>$val){
  $lines[$key] = explode('|', $val);
}
echo $lines[0][3]; //shows line
echo $lines[1][1]; //shows is
?>
Jim
Forum Contributor
Posts: 238
Joined: Fri Apr 19, 2002 5:26 am
Location: Near Austin, Texas

Post by Jim »

Excellent dude.

Next question - how do I ensure results are put on the next line at every submission?

Thanks man.
Jim
Forum Contributor
Posts: 238
Joined: Fri Apr 19, 2002 5:26 am
Location: Near Austin, Texas

Post by Jim »

Never mind last q :)
Post Reply