PDA

View Full Version : PHP: how to find a line feed in a text


Arjan
02-22-2006, 02:59 PM
I have a text in $mytext

Now I want to cut that text after the 5th line.
Doing so by estimating that every line is, say 100 chars, doesn't allways work.

Like in this case where every line has a line feed:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7

How can I detect (and count) the line feeds in this text and determine which one is the 5th, so I know where to cut my text?

Code Monkey
02-23-2006, 01:27 AM
$mytext = <<<HDOC
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
HDOC;
$temp_array = explode("\n", $mytext);


Eplode the page into an array using the newlines.

Then of course, line five is

echo $temp_array[4];


You can also loop through it and delete lines before or after line five. You didn't specify.


$line_count = count($temp_array);
for($i = 0; $i < $line_count; $i++)
{
if($i == 4)
{
echo $temp_array[$i];
}
}



$line_count = count($temp_array);
$new_text = '';
for($i = 5; $i < $line_count; $i++)
{
$new_text .= $temp_array[$i]."\n";
}
echo $new_text;



$line_count = count($temp_array);
$new_text = '';
for($i = 0; $i < 5; $i++)
{
$new_text .= $temp_array[$i]."\n";
}
echo $new_text;

Marco van Herwaarden
02-23-2006, 08:17 AM
Tip: also have a look at array_slice()

Arjan
02-23-2006, 01:21 PM
Thanks, that should help me out.