Line with regex when breaking first line

I would like to split a line in the first line break, and not on the first empty line

' /^(.*?)\r?\n\r?\n(.*)/s' (first empty line)

So, for example, if I have:

$ str = '2099 test \ nYou make sure you want to continue \ n some other line here ...

 match[1] = '2099 test' match[2] = 'Are you sure you want to continue\n some other string here...' 
+4
source share
6 answers

preg_split() has a limit parameter that you can take advantage of. You can just do:

 $lines = preg_split('/\r\n|\r|\n/', $str, 2); 
+11
source
 <?php $str = "2099 test\nAre you sure you want to continue\n some other string here..."; $match = explode("\n",$str, 2); print_r($match); ?> 

returns

 Array ( [0] => 2099 test [1] => Are you sure you want to continue some other string here... ) 

explode last parameter - the number of elements that you want to split into a string.

+5
source

Usually just delete \r?\n :

 '/^(.*?)\r?\n(.*)/s' 
+1
source

You can use preg_split as:

 $arr = preg_split("/\r?\n/",$str,2); 

Look at ideone

+1
source

First line break:

 $match = preg_split('/\R/', $str, 2); 

First blank line:

 $match = preg_split('/\R\R/', $str, 2); 

Handles all the different ways to perform line breaks.

There was also the question of splitting the second line at break. Here is my implementation (maybe not the most efficient ... also note that it replaces some line breaks with PHP_EOL )

 function split_at_nth_line_break($str, $n = 1) { $match = preg_split('/\R/', $str, $n+1); if (count($match) === $n+1) { $rest = array_pop($match); } $match = array(implode(PHP_EOL, $match)); if (isset($rest)) { $match[] = $rest; } return $match; } $match = split_at_nth_line_break($str, 2); 
+1
source

You may not even need to use regex. To get only split lines, see:

What is the easiest way to return the first line of a multiline string in Perl?

0
source

Source: https://habr.com/ru/post/1343784/


All Articles