Search code snippets, questions, articles...

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);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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?