Question

In PHP, how do I return the 6th or 5th or 4th lines from a string that looks like below.? A new line is define with the char <br />.

So, if i have a string like this

$lines = 4;
$lyrics = 'line 1<br />line 2<br />line 3<br />line 4<br /><br />line 5<br />line 6<br />line 7<br />line 8';

it should return

line 1<br />line 2<br />line 3<br />line 4

if i have

$lines = 4;
$lyrics = 'line 1<br />line 2';

it should return

line 1<br />line 2
Was it helpful?

Solution

Split the string into an array using explode(), use array_slice() to get the first n elements of the newly created array. Finally join them again.

$n = 4;
$lyrics = 'line 1<br />line 2<br />line 3<br />line 4<br /><br />line 5<br />line 6<br />line 7<br />line 8';
$lines = explode('<br />', $lyrics);
echo implode('<br />', array_slice($lines, 0, $n));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top