How can PHP functions like explode() and count() be utilized to extract a specific number of lines from a text variable?
To extract a specific number of lines from a text variable in PHP, you can use the explode() function to split the text into an array of lines and then use the count() function to determine the total number of lines. You can then extract the desired number of lines by using array slicing.
$text = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5";
$lines = explode("\n", $text);
$num_lines = 3; // Specify the number of lines to extract
if (count($lines) >= $num_lines) {
$extracted_lines = array_slice($lines, 0, $num_lines);
foreach ($extracted_lines as $line) {
echo $line . "\n";
}
} else {
echo "Not enough lines in the text.";
}