In this PHP tutorial, you shall learn how to split a given string by new line separator using explode() function, with example programs.

PHP – Split String by New Line

To split a string by new line delimiter in PHP, use explode() function. Call explode() and pass the new line '\n' separator string, and given string as arguments.


The syntax to split the string str by new line using explode() function is

explode('\n', $str)

The function returns an array of values.



1. Split string containing multiple lines to an array of lines

In this example, we will take a string str that has multiple lines. We split this string into an array of values where each value is a line.

PHP Program

  $str = 'apple is red\nbanana is yellow\ncherry is red\nmango is yellow';
  $values = explode('\n', $str);
  foreach ($values as $x) {
      echo $x;
      echo '<br>';



In this PHP Tutorial, we learned how to split a string by new line delimiter, using explode() function.