php

Split string by new line PHP

We are using regex to split the string by new line in PHP.

$str = "Line number 1
Line number 2";

$str_parts = preg_split("/\r\n|\r|\n/", $str);

The best way to split or explode the string by a new line is by using regex function preg_split. In the code snippet, we are using two lines in a $str variable and getting its lines into an array $str_parts.

Was this helpful?